HTML5 Canvas, Pixel Compositing, Transparency, and why all the trivia!

One thing I really hate about new technology are all the early adopters who incessantly post the same trivial examples. They cross link them too. So you can go from one page to the next, and see essentially the same example, just with the bits renamed or moved around.

At a certain point, I got it into my head that I wanted to make a quickie HTML5 App that works with my Intuous5 Wacom Pad. Wacom has a web plugin that let’s you get data about pen pressure and so on from the tablet. So I started to work on it, and found the said trivial examples and started mashing something up. Pretty soon it became apparent that if I wanted my lines to look good, I might have to anti-alias them, or so I am trying, I don’t know if it will work, because I just spent the better part of 2 hours looking for a solution to a simple problem.

If you look for examples of pixel level manipulation for HTML5 Canvas, you will find the same trivial examples over and over again, which basically say:

If you actually want a full trivial example, use google, they abound.

The problem with the above is: it replaces the entire pixel, all the way to the background, erasing any colors beneath it. The alpha channel of the pixel doesn’t make it transparent to what was under the pixel, it makes it transparent to the background (probably white).

What I wanted to do was composite the new pixel ontop of the old pixel, and have the alpha value indicate how much of the other color should show through.

After much searching, I came up with this:

This seems to work as I had hoped, I mucked about with the color and it seems to do right.

A point here: alpha is a value between 0..1, and notice d[3] is set to 255. That’s because the pixel alpha channel shows through the real background, not the background I have painted, so you need to keep that as 255 and precompute the alpha.

About Jason

I am a 31 year old programmer living in the south of France. I currently work actively in the fields of Ruby/PHP/Javascript and server/website administration.
This entry was posted in HTML5, HTML5 Canvas, Javascript Tutorials, Topics, Tutorials, Web Design and tagged , , , , , , . Bookmark the permalink.