Game Development Reference
In-Depth Information
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);
pixels instanceof ImageData; // True
pixels.data instanceof Uint8ClampedArray; //
True
pixels.width == canvas.width; // True
pixels.height == canvas.height; // True
// Insert pixel data into canvas context
ctx.putImageData(pixels, 0, 0);
};
img.src = "img/html5-logo.png";
To get the pixel data representing whatever is currently drawn in the canvas, we can
use the function getImageData . The four parameters are the x and y offset on the
source image, along with the width and height to be extracted. Note that the out-
put from this function is an object of type ImageData , which has three attributes,
namely, width, height, and a typed array with the actual pixel information. As men-
tioned earlier in the chapter, this typed array is of type Uint8ClampedArray , where
each element can only be an integer with a value between 0 and 255 inclusive.
The pixel data is a buffer of length ( canvas.width x canvas.height x 4 ).
That is, each four elements represent one pixel, representing the red, green, blue,
and alpha channels of the pixel in this order. Thus, in order to manipulate an image
through this canvas API, we perform various calculations on this pixel buffer, which
we can then put back in the canvas using the putImageData function.
The three parameters of putImageData are the ImageData object, along with the
x and y offset on the destination canvas. From there, the canvas will render the im-
Search WWH ::




Custom Search