Vanilla JavaScript images in canvas


Learn how to add, and modify images in canvas

17 Sep, 2020 · 2 min read

Another day of canvas exploration, and today we’ll be looking at using images in our canvas.

We use the getImageData function to read an image, which will return an imageData object that copies pixel data.

For each pixel, we will get the rgba values.

Today we will explore getting these values from an image and inverting them.

The result is this Codepen.

See the Pen Vanilla JavaScript images in canvas by Chris Bongers (@rebelchris) on CodePen.

You can find my other articles about canvas modification on the following links:

Canvas adding an image

Let’s first set up our HTML structure so we have an image and a canvas to render our new image.

<canvas id="canvas" width="200" height="200"></canvas>

There we go. We have our image, which is 200x200, and our canvas which I made for this exercise.

Next, we need to define our image and canvas in JavaScript.

const img = document.getElementById('eeveelutions');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

Now we can render the image as is in our canvas:

Note: We have to wait for the image to load. Else we will see a white image

img.onload = function () {
  ctx.drawImage(img, 0, 0);

But that’s for this point, not useful, so let’s get the imageData.

const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);

Note: For Codepen I have to add img.crossOrigin="anonymous"; for CORS issues.

We then get an imageData object that looks something like this:

imageData object

As mentioned before, these are rgba values, so every four records is one-pixel value containing:

  • red (0-255)
  • green (0-255)
  • blue (0-255)
  • alpha (0-255, 0 = transparent, 255 = fully visible)

So to invert each pixels value, we need to do the following calculation for each of the three colors (alpha will keep 255)

  • red = 255 - old value
  • green = 255 - old value
  • blue = 255 - old value

In code, it will look like this:

for (i = 0; i <; i += 4) {[i] = 255 -[i];[i + 1] = 255 -[i + 1];[i + 2] = 255 -[i + 2];[i + 3] = 255;

The last step is to put this modified data back on our canvas.

ctx.putImageData(imgData, 0, 0);

There we go. We learned how to place an image on a canvas and modify its pixel data! 🔥

Image credit Zerochan

Browser Support

The imageData API, as well as canvas, have excellent support!

HTML Canvas imageData support

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter