Color Transform for HTML5 Canvas

Interest in more information on applying color transformations with HTML5 Canvas came from my last post. If you’re coming from Flash, the concept of color transforms should be pretty familiar. The canvas method works pretty much the same way that Flash’s ColorTransform object worked (or what the color tint interface configured within the Flash IDE). All code needed is below; this snippit is largely based on the operation from easel.js.

// Apply color transform.
var r = 115, // Red tint (0-255)
    g = 208, // Green tint (0-255)
    b = 189, // Blue tint (0-255)
    t = 0.6, // Tint strength (0-1)
    ctx = document.getElementById('myCanvas').getContext('2d'), // Get the drawing context of your canvas element.
    img = ctx.getImageData(0, 0, 100, 100), // Pull a rectangle of image data from context
    data =, // Image image data array.
    len = data.length; // Length of data array.

// Loop through image data array.
// Apply color trasform to each block of RGBA values.
// Applied as: c = c * cmodifier + coffset.
for (i = 0; i < len;) {
    data[i] = data[i++] * (1-t) + (r*t);
    data[i] = data[i++] * (1-t) + (g*t);
    data[i] = data[i++] * (1-t) + (b*t);
    i++; //data[i] = data[i++] * 1 + 0; << skip alpha component. Adjust as needed.

// Restore image data within the canvas.
ctx.putImageData(img, 0, 0);

2 comments so far

  1. Keng on

    Hi! I checked out your fishing game. Thank you for making this available. I was wondering if you can explain one thing. There is no tag on your index.html but in your javascript you can still access the canvas. How does that work?

    • bigmac on

      Hey Keng, thanks for the comment. All canvas elements used by the game are created dynamically using JavaScript; most are not even added to the DOM (they’re simply used as a pasteboard for managing pixels in memory).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: