HTML5 and transparency

As an experiment I decided to create a couple of gears that would appear as an overlay on a web page.

My thinking was that I might use HTML5 to create UI controls that could be incorporated into a web form as slider bars, dials or charts, where there was a need for functionality that the basic HTML controls couldn’t provide.

I ran into a few issues:

  1. First, I wanted the gear to have the appearance of rotating. I did this by using the translate function to set the origin to the center axis of the gear. The rotate function could then be used to rotate the canvas around that origin. 2*Math.PI is a complete circle.
  2. I was using a hidden canvas as a buffer to draw the gear, then drawing the completed gear on the visible canvas using drawImage. The axis was causing me issues, and I had some trouble getting the transparency to work correctly, so I decided to add another hidden buffer canvas. From my reading it seems like there is an issue with the alpha byte in canvas that controls transparency and some html5 functions (IE: clearRect), so I decided to use get getImageData and putImageData functions to copy the gear image from the first buffer canvas to the second. I used this copyImage function to do so.

    Note that the copyImage function accepts a transparentColor value. If present, this value determines the color in the copied image that will become transparent.
  1. Finally, I use the drawImage function to copy the image from the buffer to the final canvas. I use drawImage here rather than copyImage as copyImage considers the entire canvas when determining transparency. IE: the transparent part of an image will show the background behind the canvas, regardless of whether graphics were previously written to that part of the canvas.

    Your browser doesn't support canvas.
var transparentColor = {
   r : 255,
   g : 255,
   b : 255
};

function copyImage(
        srcCtx,
        srcX,
        srcY,
        srcWidth,
        srcHeight,
        destCtx,
        destX,
        destY,
        transparentColor)
    {
        // read pixels from source
        var pixels = srcCtx.getImageData(srcX, srcY, srcWidth, srcHeight);

        // iterate through pixel data (1 pixels consists of 4 ints in the array)
        for(var i = 0, len = pixels.data.length; i < len; i += 4){
            var r = pixels.data[i];
            var g = pixels.data[i+1];
            var b = pixels.data[i+2];

            // if the pixel matches our transparent color, set alpha to 0
            if(transparentColor!=undefined)
                if(r == transparentColor.r && g == transparentColor.g && b == transparentColor.b){
                    pixels.data[i+3] = 0;
                }
        }

        // write pixel data to destination context
        destCtx.putImageData(pixels,destX,destY);
    };

Be the first to comment

Leave a Reply