如何在用户点击图像时使用JavaScript或jQuery读取图像的像素?
问题描述:
当用户点击图像时,如何使用JavaScript或jQuery读取图像像素的颜色? (当然,我们通过订阅click事件得到了这个像素的(x,y)值。)
How can I use JavaScript or jQuery to read the color of a pixel of an image when the user clicks on it? (of course we have the (x,y) value of this pixel by subscribing to the click event).
答
如果你可以在画布元素中绘制图像,然后您可以使用 getImageData
方法返回包含RGBA值的数组。
If you can draw the image in a canvas element then you can use the getImageData
method to return an array containing RGBA values.
var img = new Image();
img.src = 'image.jpg';
var context = document.getElementById('canvas').getContext('2d');
context.drawImage(img, 0, 0);
data = context.getImageData(x, y, 1, 1).data;