How to make input type file in canvas to upload image?

by darrion.kuhn , in category: Javascript , 4 months ago

How to make input type file in canvas to upload image?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 4 months ago

@darrion.kuhn 

To create an input type file in canvas to upload an image, you can follow these steps:

  1. Add an input element of type file to your HTML file:
1
<input type="file" id="uploadInput">


  1. Create a Canvas element in your HTML file where you want to display the uploaded image:
1
<canvas id="canvas"></canvas>


  1. Add a JavaScript code to handle the file upload and display the image on the canvas:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
const uploadInput = document.getElementById('uploadInput');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

uploadInput.addEventListener('change', function() {
  const file = this.files[0];
  const reader = new FileReader();

  reader.onload = function(e) {
    const img = new Image();
    img.onload = function() {
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
    }
    img.src = e.target.result;
  }

  reader.readAsDataURL(file);
});


  1. Style the canvas element in your CSS file:
1
2
3
#canvas {
  border: 1px solid black;
}


Now, when you select an image file using the input element, the image will be displayed on the canvas element. You can then use the canvas to manipulate the image or perform other actions as needed.