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

Error: Uncaught TypeError - Unable to access the 'handleClick' property of undefined within a forEach loop

I came across the following code snippet articles_list.jsx import React from 'react'; import './articles_list.css'; export default class ArticlesList extends React.Component { constructor(props) { super(props); this.state ...

Successfully resolving the API without encountering any response errors, even after sending a response

Once the data is successfully saved in the database and the image upload is completed, I am attempting to send res.json. However, I keep encountering the error message API resolved without sending a response for /api/auth/registeration, this may result in ...

Distinguishing Between server.listen() and app.listen() in Google Apple Engine

I am currently working on a NodeJS + Express application. While running it locally, I have the following code: const port = 3001; server.listen(port, () => { console.log(`App listening on port ${port}`); }); However, when deploying to GAE, I switch ...

Developing a dynamic web application using the Django framework along with the Vue.js library and Highcharts for

I am currently working on a data visualization web app using Django, Highcharts, and JQuery. I have recently transitioned from JQuery to Vue JS and I am struggling with fetching JSON data from a specific URL. Below is the code snippet: Template <!doc ...

Encountering an error when attempting to access an object property dynamically by using a passed down prop as a variable in Vue 2 & Vuex

I have been struggling for hours to find a solution to this problem, but so far I've had no luck. I've looked at these two questions, but they didn't provide the answers I needed: Dynamically access object property using variable Dynamical ...

"What is the process for developing a Web-component with Vue and typescript that can be used in

Utilizing vue-custom-element, I have successfully created a Web component in Vue and integrated it into Angular. This setup operates seamlessly for Vue+js: import Vue from 'vue' import Calculator from './components/Calculator.vue' impo ...

Tips for effectively managing 404 errors in Angular 10 with modular routing

I'm facing challenges with handling 404 pages within an Angular 10 application that utilizes modular routing architecture. Here is the structure of my code: |> app |-- app.module.ts |-- app-routing.module.ts |-- app.component{ts, spec.ts, scss, ht ...

You can only set headers once during the initial request; any additional attempts to set headers will result in an

I encountered a specific issue with the error message "Can't set headers after they are sent". Here is the relevant code snippet: create: (request, response, next) -> socket = @app.socket # # This method will be used to call the right method ins ...

Angular 6 implement a waiting function using the subscribe method

I need to make multiple calls to a service using forEach, where each call depends on the completion of the previous one. The code is as follows: itemDefaultConfiguration.command = (onclick) => { this.createConfiguration(configuration.components); ...

Modify the array dynamically within the Factory

I am currently working on a simple app where I want to display embed videos with the click of a button. It was quite challenging for me to dynamically bind my embed players, but I managed to do it successfully. I created a factory that contains my data in ...

How to retrieve the user-agent using getStaticProps in NextJS

Looking to retrieve the user-agent within getStaticProps for logging purposes In our project, we are implementing access and error logs. As part of this, we want to include the user-agent in the logs as well. To achieve this, we have decided to use getSta ...

issue with angular directive not properly binding data

I am curious about the following code: HTML: <div class="overflow-hidden ag-center" world-data info="target"></div> js: .directive('worldData', ['$interval', function($interval) { return { scope: { ...

What is the best way to retrieve the value of a text box in VUEjs using its unique identifier?

In my form, there are a total of two text boxes with predefined values. However, I am looking for a way to retrieve the value of one specific textbox based on the entered ID number. For example, if I input "1," I expect to see the value of text box 1 only ...

Is it possible to compare two charts in Chart.js in a way that avoids the issue of small values appearing as large as big values?

I am currently working on a production tracking page that features multiple charts. I want to avoid inconsistencies in tracking at first glance. Is there a way to achieve this using chart.js? If not, what would be the best approach to address this issue? ...

Use the accelerometer in JavaScript and Cordova to control the movement of an object, such as a ball

Having trouble figuring out how to move a ball using the accelerometer. Any tips on combining the accelerometer values with the ball movement? Waiting for accelerometer... <div id="heading">Waiting for heading...</div> <div id="ball" ...

Tips for updating a column with just one button in AngularJS

On my list page, there is an Unapproved button. I am new to angular and struggling to figure out how to retrieve the post's id and update the corresponding column in the database to mark it as approved. Can someone provide guidance on how to accomplis ...

Troubleshooting why the Angular innerHTML function is failing to render the specified

I'm encountering this problem where I am receiving a string const str = '<p>Please ensure Process Model diagram represents Functions adequately (boxes that represent an activity or group of activities that produce an outcome):</p>< ...

Guide on adding a post type via the command line: Issue encountered - Anticipated POST console HTML error

Facing Error: EXPECTED POST in JQuery Ajax Call Encountering the same issue as mentioned in the provided link. The need is to switch from GET to POST, but direct alteration of ajax code is not feasible. It must be done dynamically using JavaScript through ...

Combining multiple AngularJS expressions to form a URL within an interpolation statement

While this explanation may be lengthy, I appreciate your patience as I try to articulate the issue at hand. The error I'm currently encountering is as follows: Error: [$interpolate:noconcat] Error while interpolating: Strict Contextual Escaping disa ...

What is the best method for inserting a 'Placeholder' in an Angular datePicker?

Looking for assistance with placing placeholder text inside an Angular datePicker, specifically wanting to display 'From' and 'To' labels within the datePicker. datePicker I am a novice when it comes to Angular development - can someon ...