HTML and CSS Reference
In-Depth Information
Sometimes you may want to access the pixel at a specific coordinate in the image. Here's how you can
determine its offset in the image data array:
var offset = (xpos + ypos * imagedata.width) * 4;
Once you have the offset index, you can access the pixel's component colors as before.
Painting pixel data
To paint an ImageData object onto the canvas, call context.putImageData(imagedata, x, y) , where
x and y specify the top-left corner of the canvas to start drawing.
A pixel can be changed by isolating it in the image data array and assigning new values to its color
components. The updated pixel values can be painted to the canvas by passing it as the first argument to
putImageData .
For example, to remove the red color channel from an image on the canvas, iterate over each pixel, setting
its red component to 0:
var imagedata = context.getImageData(0, 0, canvas.width, canvas.height),
pixels = imagedata.data
for (var offset = 0, len = pixels.length; offset < len; offset += 4) {
pixels[offset] = 0; //red
pixels[offset + 1] = pixels[offset + 1]; //green
pixels[offset + 2] = pixels[offset + 2]; //blue
pixels[offset + 3] = pixels[offset + 3]; //alpha
}
context.putImageData(imagedata, 0, 0);
Here, the image data array is assigned to pixels . (JavaScript objects—and hence arrays—are assigned
by reference, so a change to the pixels array is a change to imagedata.data , as they are the same
object.) We iterate over the pixels, jumping four elements at a time, and assign the values for the color
components. When we are finished, the updated imagedata object is drawn back to the canvas.
We'll use the same pixel iteration process in the next example. First, some red, green, and blue stripes are
drawn to the canvas so we have some image data to work with. Then, new color values are calculated for
each pixel by inverting the old ones, keeping in mind each component must be an integer from 0 to 255.
Here's the code for exercise 13-invert-color.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Invert Color</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
window.onload = function () {
 
Search WWH ::




Custom Search