HTML and CSS Reference
In-Depth Information
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
//draw some red, green, and blue stripes
for (var i = 0; i < canvas.width; i += 10) {
for (var j = 0; j < canvas.height; j += 10) {
context.fillStyle = (i % 20 === 0) ? "#f00" : ((i % 30 === 0) ? "#0f0" : "#00f");
context.fillRect(i, j, 10, 10);
}
}
var imagedata = context.getImageData(0, 0, canvas.width, canvas.height),
pixels = imagedata.data;
//pixel iteration
for (var offset = 0, len = pixels.length; offset < len; offset += 4) {
//invert each color component of the pixel: r,g,b,a (0-255)
pixels[offset] = 255 - pixels[offset]; //red to cyan
pixels[offset + 1] = 255 - pixels[offset + 1]; //green to magenta
pixels[offset + 2] = 255 - pixels[offset + 2]; //blue to yellow
//pixels[offset + 4] is alpha (the fourth component)
}
context.putImageData(imagedata, 0, 0);
};
</script>
</body>
</html>
This is a relatively simple transformation, but as you might expect, effects like these can get very
complicated, and very processor intensive—especially when applied to animations. If you're making
something other than a fun demo, be mindful of the burden you may place on the user's machine.
Converting a color image to grayscale is another effect we can calculate easily. The luminance of each
pixel is calculated, where the color components are weighted to reflect the perceived intensity of different
light wavelengths. Just in case you think we're making these numbers up as we go along, the formula is, in
fact, defined by the International Commission on Illumination . Replace the pixel iteration for loop from the
last example with this one (document 14-grayscale.html ):
//pixel iteration
for (var offset = 0, len = pixels.length; offset < len; offset += 4) {
var r = pixels[offset],
g = pixels[offset + 1],
b = pixels[offset + 2],
y = (0.2126 * r) + (0.7152 * g) + (0.0722 * b); //luminance
pixels[offset] = pixels[offset + 1] = pixels[offset + 2] = y;
}
Now it looks like the striped image is being displayed on an old black-and-white television.
Let's make the next example more dynamic by introducing some user interactivity. We can use the mouse
position to affect the image data, and put the pixel processing in an animation loop to work on each frame.
Search WWH ::




Custom Search