Skip to content

Canvas Images

One of the features of the <canvas> element is the possibility of using images. These can be used for different purposes. You can use external images in any format supported by the browser (e.g., PNG, GIF, or JPEG). As a source, you can also use the image created by other canvas elements.

Importing images into a canvas is a two-step process:

  1. Get a reference to another canvas element or an HTMLImageElement object as a source.
  2. Draw an image on the canvas with the drawImage() function.

As an image source, the canvas API can use any of the following data types:

Data TypeDescription
HTMLImageElementThese are images created with the Image() constructor, or any <img> element.
SVGImageElementThese are images embedded with the <image> element.
HTMLVideoElementAn HTML <video> element as an image source takes the current frame from the video and uses it as an image.
HTMLCanvasElementAs an image source, you can use another <canvas> element.

These sources together are referred to by the type CanvasImageSource.

There are many ways to get images for use on canvas.

Using images from the same page

You can get a reference to images on the same page with the canvas with one of the following:

  • The document.images collection
  • The document.getElementsByTagName() method
  • The document.getElementById() method if you know the ID of the image you want to use

Using images from other domains

Using the <img> element with the crossorigin="anonymous" attribute, you can request permission to load an image from another domain. If the hosting domain allows cross-domain access via CORS headers, you can use the image in your canvas without tainting it.

Note If you draw a cross-origin image without proper CORS setup, the canvas becomes "tainted". A tainted canvas restricts access to its data (e.g., toDataURL() will throw an error).

Using other canvas elements

Other canvas elements can be accessed using either the document.getElementById() or document.getElementsByTagName() method.

Embedding an image via data: URL

Data URLs allow specifying an image as a Base64 encoded string of characters directly in the code. The data URL’s advantage is that the resulting image is available immediately. It is also possible to wrap all your CSS, HTML, JavaScript, and images in one file.

However, there is also a disadvantage: the image is not cached, and the encoded url can be too long for larger images.

Creating an image from scratch

You can also create a new HTMLImageElement object in your script. For this, use the Image() constructor:

Creating an image from scratch

js
var img = new Image();
img.onload = function() {
  ctx.drawImage(img, 0, 0);
};
img.src = 'myImage.png';

The image begins loading when src is set. To ensure drawImage() is called only after the image is ready, use the onload event handler.

The drawImage() function

Once a reference to the source object image is available, you can use the drawImage() method. This method has the following variants:

  • drawImage(image, x, y),
  • drawImage(image, x, y, width, height),
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight).

The basic form is drawImage(image, x, y).

In the following example, we use the document.getElementById() method to get a reference to the image and then use the drawImage() function to draw the image.

Example of drawing an image with the drawImage() function:

Example of drawing an image with the drawImage() function

html
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h2>Image</h2>
    <img id="photo" src="https://www.w3docs.com/uploads/media/default/0001/01/25acddb3da54207bc6beb5838f65f022feaa81d7.jpeg" alt="Aleq" width="200" height="185" />
    <h2>Image with canvas:</h2>
    <canvas id="exampleCanvas" width="240" height="225" style="border:2px solid #cccccc;">
      Your browser doesn't support the canvas tag.
    </canvas>
    <script>
      window.onload = function() {
        var canvas = document.getElementById("exampleCanvas");
        var ctx = canvas.getContext("2d");
        var img = document.getElementById("photo");
        ctx.drawImage(img, 20, 20);
      };
    </script>
  </body>
</html>

DANGER

SVG images must define the width and height in the root <svg> element.

Using frames from a video

It is also possible to use frames from a video that is presented by a <video> element, even when the video is not visible. E.g., if you have a <video> element with the ID "videoCanvas", do the following:

Example of drawing a video with canvas:

Canvas Images

html
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h2>Video</h2>
    <video controls id="videoCanvas" controls width="350" autoplay>
      <source src="https://www.w3docs.com/build/videos/arcnet.io(7-sec).mp4" type="video/mp4" />
    </video>
    <h2>Canvas  draws the current video:</h2>
    <canvas id="exampleCanvas" width="310" height="190" style="border:1px solid #d3d3d3;">
      Your browser doesn't support the canvas tag.
    </canvas>
    <script>
      var v = document.getElementById("videoCanvas");
      var c = document.getElementById("exampleCanvas");
      var ctx = c.getContext("2d");
      var animId;
      function drawFrame() {
        ctx.drawImage(v, 5, 5, 300, 180);
        animId = requestAnimationFrame(drawFrame);
      }
      v.addEventListener("play", function() {
        animId = requestAnimationFrame(drawFrame);
      }, false);
      v.addEventListener("pause", function() {
        cancelAnimationFrame(animId);
      }, false);
      v.addEventListener("ended", function() {
        cancelAnimationFrame(animId);
      }, false);
    </script>
  </body>
</html>

Practice

What are the essential steps for drawing an image onto the Canvas in HTML?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.