How to upload and draw an image on HTML canvas?

This tutorial is on how to upload a picture to canvas from file using javascript. A tutorial on drawing an image from internet on HTML canvas is available here. (Draw image from internet on canvas)The complete code is provided just below and the steps on how to upload and draw image on canvas using javascript follows.

Complete Code

You can learn the complete breakdown of the code below.

  • 1. Defining input and canvas element
  • 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.

  • 2. Defining event listener for image upload
  • 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.

  • 3. Loads the image and convert into DataURL
  • Here, we read the image path from 'e.target.files[0]' 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.

  • 4. Draws the converted image on canvas
  • 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.