How to upload and draw an image on HTML canvas?
You can learn the complete breakdown of the code below.
First, we need to create an input box to upload image from the computer. In the above code, the parameters type="file" indicates that the input box accepts files as input. "image/*" indicates that it accepts images only in all formats. Replacing * with jpeg or png allows images in jpeg or png formats respectively. We also define the html canvas size or dimensions here.
We also define a canvas element on which the image will be displayed.
Next, we define the input object to a variable(named imgInput) and an event listener is assigned to it. When the event listener detects a change in input box status(i.e when user uploads an image), it triggers a function inside the loop which is shown below.
Here, we read the image path from 'e.target.files' assigned to a variable named imageFile. You can also use console.log e.target.result to print the file's text information. Now, we define a FileReader() to a variable reader and defines how to call the image - reader.readAsDataURL (imageFile). In order to make sure that the image is successfully loaded before moving further, we use "reader.onloadend" function. Now, we need to convert it into a DataURL which is a URI scheme commonly used to embed images in HTML and CSS.
Once the converted image is fully loaded, we define an image object(named as myImage) and assigns the converted image to it. We also defines the canvas(named as myCanvas) and context(named as myContext). The context object is an object with properties and methods that helps us to do actions in the canvas. Optionally, you can assign the canvas width and height as the width and height of the image. Now, all we need to do is to draw the image using drawImage() function. Here, we use toDataURL function to output the canvas image as base64 string in jpeg format at quality of 0.75. If you need a different image format such as png, or different image quality, the value of toDataURL function can be changed accordingly.
5 Simple Toggle Button Animation in HTML - Pure CSS
How to draw an image from internet on HTML canvas?
A guide on how to draw an image from internet on HTML canvas?
How to improve your SEO by effectively using Facebook meta tags?
A guide on how to improve your SEO by effectively using Facebook meta tags?