In our opinion, this is the most important element that differs from SVG. With canvas you can perform operations on pixel based artworks. You can write a new image pixel by pixel or import an image in the canvas and modify it as you need.
In this article we’ll show you some fundamentals of pixel manipulation in the canvas, and how to use this knowledge to obtain interesting effects. Let’s start from the beginning.
Importing Bitmap Image On Canvas
Now our image is in position, but we need to know more on how to manage pixels.
As perfectly described by Opera, pixels in a canvas are represented from left to right, from top to bottom. Every pixel has 4 values: red, green, blue and alpha. It’s easy to understand the power of this principle: you can work on every single pixel and change the values. It’s like editing an image by hand, instead of using a desktop application.
So, looping trough the pixels array, we’re going to get an interesting black and white effect.
Black & White Effect
There’s our black and white effect. Let’s start from the beginning of our code because it’s a little bit complex. Using the function getImageData() we store in a variable imgd our image and we’ll be able to access every single pixel by storing the data array in the pix variable. Then we use a for statement to loop through each pixel, and through each value of a single pixel. As described before, every pixel has four values: red, green, blue and alpha. So, pix[i] is red, pix[i+1] is green, pix[i+2] is blue and pix[i+3] is the alpha channel.
So, what can we use to make an image black and white? The luminance. The luminance is how much a color is luminous to the human eye and it’s used to measure the clipping white in video editing systems, for example. In video editing system a white color that “break” the screen is a white that is too white to be represented on a common TV.
This is important because by calculating the average number between red, green and blue values we could obtain a value for every pixel that represent a static mathematical representation of the color luminance.
But there’s a problem, an human eye see colors dynamically. For example, if we take similar shades of blue and green, our eyes will detect the green color more luminous than the blue. In our algorithm we could use the static average formula, but our image will be too flat, and we’ll lose a lot of color depth.
So, let’s introduce the luminance formula: red x 0.3 + green x 0.59 + blue x 0.11.
Has anyone used this technique before? What do you think? See you in the comment section ;)