Image Blend modes and HTML Canvas
Image Blend modes are the methods used to determine how 2 image layers are
blended (mixed) to each other. As the digital images are stored in pixel, which
are represented by numerical values, there are a large number of possible ways
for blending based on the mathematical functions. With the help of Canvas API,
now we can easily retrieve the images, export all the pixels on the image,
apply blending effect, calculate to get the new blended
pixels, export and display the new image on the web or save to server.
In this post, I will demonstrate some basic steps for applying Image Blend modes
using HTML canvas API.
Wikipedia already listed some popular blending methods here
Assume that we have two image layers, top layer and bottom layer. For each loop,
a is the value of a color channel in the underlying layer and b is that
of the corresponding channel of the upper layer, we got the function for
calculating the new pixel ƒ(a, b).
The steps for generating the new blended image from the two images are
- First, retrieve those two images
- Create two separate canvases with the same size and draw those two images into
the corresponding canvas.
- Get all the pixel data from the two canvases.
- Loop through each pixel, apply the blending function to create a new pixel and
store it inside an array
- Create a new canvas with the same size, use the blended pixel data to draw the
blended image on that new canvas
- Export the canvas to image, file to save to server or to local computer.
Note: I mentioned that we need to create two canvases with the same size.
However, that is just to make it easy for the demonstration purpose. You can
still generate two canvases with different size, but you will need to change the
calculation function a bit.