Delete the generated thumbnails from the input JavaScript file

One issue I'm facing is that I have written JavaScript code to generate a thumbnail when a user uploads an image. Now, I would like to implement a feature that allows the user to click on an "X" button to delete the uploaded image.

This is the existing code:

 var imageLoader = document.getElementById('fUpload2');
    imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas2');
var ctx = canvas.getContext('2d');


function handleImage(e){

    var reader = new FileReader();
    reader.onload = function(event){
        var img = new Image();
        img.onload = function(){
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img,0,0);
 document.getElementById("imageCanvas2").style.height =  canvas.height;
 document.getElementById("imageCanvas2").style.maxWidth = "200px";
 document.getElementById("imageCanvas2").style.maxHeight = "200px";
 document.getElementById("imageCanvas2").style.border = "1px solid #000";
 
}
        img.src = event.target.result;
var alte= canvas.height;
    }
    reader.readAsDataURL(e.target.files[0]);     
}
   .image-upload-gal > input {
    display: none;
}
   <div class="well"> 
  <form class="form-horizontal" role="form" method="post" action="/ServiceUpload.php" enctype="multipart/form-data">
     
      <div class="form-group" style="padding:14px;">
                            <div class="image-upload-gal" >
    <label for="fUpload2">
        Add foto
    </label>
   <input type="file" name="fUpload" id="fUpload2"  />
  <br>
  
   <canvas id="imageCanvas2" ></canvas>
 
     
</div>
      </div>
      <button class="btn btn-primary pull-right" type="submit" value="f_upload" name="up" style="margin-top: -20px;">Submit Photo</button>
      
  </form>
      </div>

In addition to this code, here is another piece of code (it's a long story :D)

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('upload').addEventListener('change', handleFileSelect, false);
.thumb {
    height: 180px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
  }

input{
  
  display:none;
  }
      
                 
    <div class="image-upload" >
<label for="upload">
       Add foto
    </label>
<input type="file" id="upload" name="fUpload"  />
 <input type="hidden" name="up" value="f_upload" />
<output id="list"></output>
</div>
                        
     
     <button class="btn btn-primary pull-right" type="submit" value="newpost" name="NewPost" style="margin-top: -10px;">Submit</button>
     </form>

Answer №1

To remove an image, simply add an onclick event to a span that contains an "x".

<span id="deleteImage">X</span>

After adding the onClick handler, remember to clear the canvas since the image is not saved anywhere else in the code.

document.getElementById("deleteImage").onclick = function(){
    canvas.clearRect(0, 0, canvas.width, canvas.height);
}

Updated: If you want to clear the canvas directly, here's how you can do it.

canvas = document.getElementById("imageCanvas2");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Link Array with Google Charts

I've been struggling for a long time to connect this array to a Google chart with no success. I would really appreciate some assistance in identifying what mistake I've made. I have created a jsfiddle where the array appears to be correct, and wh ...

Nuxt.js static pages with relative URLs

I am currently working on developing static pages with Nuxt.js (MPA). After executing the generate command, I noticed that all the URLs in the <nuxt-link> tag start from the root directory, specifically /. For instance, my project structure looks lik ...

The redirection to the HTML page happens too soon, causing the ASYNC functions to fail in saving the user's image and data to the server

Hey everyone! I'm facing an issue with async/await functions. Here's the code snippet from my backend where I'm trying to save details of a newly registered user. I'm puzzled as to why the Redirect() function is executing before the f ...

In the world of NodeJS, the 'Decimal' module functions just as effectively when written as 'decimal'

I recently installed and started using the package decimal.js in my NodeJS project. If you're interested, you can find more information on this package here. What I found interesting is that while all the examples recommend using Decimal, I also not ...

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

Ensure Focus Retention Upon Clicking Inside Iframe with li a:focus

How can I prevent my ul.SideNav_Main li a:focus class from losing focus when I click on the iframe or elsewhere on the page? Shouldn't it maintain focus until I click on another URL in the list? Is it possible to solve this issue with just CSS, or wo ...

Issues with React - Material UI Menu functionality

I'm encountering an issue with the menu/menu item component from material ui when trying to render it based on a condition. Here is my code snippet... const AddSelectItemButton = () => { return ( <> <Fab ar ...

What is preventing me from setting a background image in Angular 13?

Trying a different approach based on advice from Stack Overflow, I attempted the following: <div [style.background-image]="'url(https://picsum.photos/200)'"></div> Unfortunately, this resulted in no effect and the image was ...

Having trouble with reactjs and typescript? Getting the error message that says "Type 'string' is not assignable to type 'never'"?

When trying to setState with componentDidMount after an axios request is completed, you may encounter the error message Type 'string' is not assignable to type 'never'. Below is the code snippet: import * as React from 'react&apos ...

Is there a way for me to determine if a domain has been registered by the client?

I'm interested in creating a Web app that allows users to enter a domain name and then uses JavaScript to check its availability. I'm wondering if there's a method to do this without relying on my own hosting server. Is it possible to send a ...

Using JQuery, it is possible to search for elements by one specific class while excluding others

Looking for a way to target elements with a specific class, but only if they don't have another class attached to them. Here is an example: <li class="target-class exclude-class"></li> <li class="target-class exclude-class"></li& ...

Seeking a proficient Cloud Code specialist skilled in JavaScript, focused on managing installations and channels

My experience with Javascript is limited, but as I work on my application, I realize the necessity of incorporating it into Cloud Code. I have a Parse class called Groups where I store group data including Name, Description, Users, and Requests. Name, Des ...

Sending a massive video file to a node.js server and saving it in AWS S3 with ReactJS

I am currently in the process of creating an OTT platform, but I have encountered a problem while attempting to upload large files to the server. I initially attempted to store the file in a temporary folder using multer and then utilize aws-sdk s3.upload. ...

Move the DIV element to a static section within the DOM

In my Vue app, I have implemented methods to dynamically move a DIV called 'toolbox' to different sections of the DOM. Currently, the DIV is positioned on the bottom right of the screen and remains static even when scrolling. My goal is to use t ...

Using JavaScript to create an image slider

My image slideshow with prototyping is not working properly and I am struggling to fix it. I have tried binding the setInterval function but it's not working. I also attempted to wrap it, but that didn't work either. What should I do to solve thi ...

What is the best way to utilize "exports" in package.json for TypeScript and nested submodules?

Looking to leverage the relatively new "exports" functionality in Node.js/package.json for the following setup: "exports": { ".": "./dist/index.js", "./foo": "./dist/path/to/foo.js" } so that ...

Issue with Passport Google Oauth login redirection to successful route

I am currently following a tutorial on setting up Google Oauth in my Express app using Passport.js. The tutorial can be found here. Below are the routes defined in my server.js file: // Code snippet here The server.js file also imports configurations fro ...

Issue: Route.get() is expecting a callback function, but instead received an undefined object in app.js

It's puzzling why this error is occurring. I have another model with a similar route and controllers, but it's not working as expected. The error message reads: Error: Route.get() requires a callback function but got a [object Undefined] at Route ...

Setting a default value for a select option in Angular 2

I am trying to set a default value for an option, acting as a placeholder using this method. It works in pure HTML, but when I implement it with the *ngFor attribute in Angular 2, nothing is selected. Here is the code I use in pure HTML: <select name= ...

Utilizing Ajax technology to load script in Tapestry 5

I have two components, a "DirectoryViewer" and a "MediaViewer", that I created. The Directory Viewer displays a list of file names and contains a MediaViewer component to show the selected file. This setup is functioning properly. Within the DirectoryView ...