Retrieving Pixel Values from HTML Canvas
Can the contents of an HTML Canvas be queried to retrieve the color of a specific pixel?
Answer:
Unquestionably! The W3C documentation provides detailed information on pixel manipulation. Here's an example to demonstrate the inversion of an image using pixel manipulation:
<code class="javascript">var context = document.getElementById('myCanvas').getContext('2d'); // Get pixel data from specified coordinates and dimensions. var imgd = context.getImageData(x, y, width, height); var pix = imgd.data; // Invert the colors of each pixel. 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 (fourth element) } // Display the modified pixel data at specified coordinates. context.putImageData(imgd, x, y);</code>
The above is the detailed content of Can You Extract Pixel Colors from an HTML Canvas?. For more information, please follow other related articles on the PHP Chinese website!