Game Development Reference
In-Depth Information
age data as far as it can, clipping any extra data that would otherwise be drawn out-
side the canvas.
As an example of what we can do with an image, we'll take the HTML5 logo that we
drew into the canvas, and apply a gray scale function to the pixel data representing
it. If this sounds like a complex task, fear not. While there are several different for-
mulas to turn a color image into gray scale, the easiest way to do this is to simply
average the red, green, and blue values of each pixel.
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var img = new Image();
img.onload = function(){
ctx.drawImage(img, 35, 60, this.width / 2,
this.height / 2, 0, 0, canvas.width,
canvas.height);
// Extract pixel data from canvas context
var pixels = ctx.getImageData(0, 0,
canvas.width, canvas.height);
// Iterate over every four elements, which
together represent a single pixel
for (var i = 0, len = pixels.data.length; i
< len; i += 4) {
var red = pixels.data[i];
var green = pixels.data[i + 1];
var blue = pixels.data[i + 2];
var gray = (red + green + blue) / 3;
// PS: Alpha channel can be accessed at
pixels.data[i + 3]
pixels.data[i] = gray;
pixels.data[i + 1] = gray;
pixels.data[i + 2] = gray;
}
Search WWH ::




Custom Search