Accessing Pixels in HTML Canvas
Can HTML Canvas objects be interrogated to retrieve the color of specific pixels?
Answer:
Yes, you can retrieve individual pixel values from a canvas using the W3C's pixel manipulation methods.
Example:
The example below demonstrates inverting the colors of an image on the canvas:
<code class="javascript">// Obtain the CanvasPixelArray for the specified coordinates and dimensions var imgd = context.getImageData(x, y, width, height); var pix = imgd.data; // Iterate over each pixel and invert its color for (var i = 0, n = pix.length; i < n; i += 4) { pix[i ] = 255 - pix[i ]; // red pix[i+1] = 255 - pix[i+1]; // green pix[i+2] = 255 - pix[i+2]; // blue // i+3 is alpha (the fourth element) } // Display the modified ImageData at the specified (x,y) coordinates context.putImageData(imgd, x, y);</code>
The above is the detailed content of Can You Query Individual Pixel Colors from an HTML Canvas?. For more information, please follow other related articles on the PHP Chinese website!