DEV Community

Cover image for Vanilla JavaScript images in canvas
Chris Bongers
Chris Bongers

Posted on β€’ Originally published at daily-dev-tips.com

6 3

Vanilla JavaScript images in canvas

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 be exploring getting these values from an image and inverting them.

The end result is this Codepen.

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

Canvas adding an image

Let's first setup our HTML structure so we have an image and a canvas to render our new image in.

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1600016358126/bMK5IddO3.jpeg" id="eeveelutions" />
<canvas id="canvas" width="200" height="200">
Enter fullscreen mode Exit fullscreen mode

There we go, we have our image, which is 200x200 and our canvas which I made the same 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');
Enter fullscreen mode Exit fullscreen mode

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);
};
Enter fullscreen mode Exit fullscreen mode

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

const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
Enter fullscreen mode Exit fullscreen mode

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

We then get a 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 colours (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 < imgData.data.length; i += 4) {
    imgData.data[i] = 255 - imgData.data[i];
    imgData.data[i + 1] = 255 - imgData.data[i + 1];
    imgData.data[i + 2] = 255 - imgData.data[i + 2];
    imgData.data[i + 3] = 255;
}
Enter fullscreen mode Exit fullscreen mode

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

ctx.putImageData(imgData, 0, 0);
Enter fullscreen mode Exit fullscreen mode

There we go, we learned how to place an image in a canvas, and even how to modify it's pixel data! πŸ”₯

Image credit Zerochan

Browser Support

The imageData API, as well as canvas, have very good 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

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (2)

Collapse
 
madza profile image
Madza β€’ β€’ Edited

If you specifically want to explore canvas, I would suggest Meth Meth Method channel.
All projects are built in canvas, high quality content.

Collapse
 
dailydevtips1 profile image
Chris Bongers β€’

Wow awesome! Thanks for that, going to give that a follow.
Especially wanting to explore canvas for one end-goal which I'm almost at, but so far it's just so much fun working with Canvas :D

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes senseβ€”CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere β€œthank you” often brightens someone’s dayβ€”share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay