Sometimes, we want to upload image into HTML5 canvas with JavaScript.
In this article, we’ll look at how to upload image into HTML5 canvas with JavaScript.
How to upload image into HTML5 canvas with JavaScript?
To upload image into HTML5 canvas with JavaScript, we can get the image from the file input and draw it in the canvas.
For instance, we write
<input type="file" id="inp" /> <canvas id="canvas"></canvas>
to add the file input and the canvas.
Then we write
const draw = (e) => {
const canvas = document.getElementById("canvas");
canvas.width = e.target.width;
canvas.height = e.target.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(e.target, 0, 0);
};
document.getElementById("inp").onchange = (e) => {
const img = new Image();
img.onload = draw;
img.src = URL.createObjectURL(e.target.files[0]);
};
to select the file input with getElementById.
And we set its onchange property to a function that runs when we select a file.
In it, we create an Image object and set img.onload to draw.
Then we set img.src to the base64 URL of the selected image file.
draw is called when the image is loaded.
In draw, we get the canvas with getElementById.
And we set the canvas dimensions to the image dimensions with
canvas.width = e.target.width;
canvas.height = e.target.height;
e.target is the img element.
Next, we get the canvas with getContext.
And we call drawImage to draw the image onto the canvas.