我在画布上放了一个图像,当用户将鼠标移到图像上时,我希望获得该图像像素的RGB值。这是我写的代码:
<canvas id="myCanvas" width="200" height="200" style="border: red;border-style: dotted">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var destX = 0;
var destY = 0;
var imageObj = new Image();
imageObj.onload = function()
{
context.drawImage(imageObj, destX, destY);
};
imageObj.src = "zain.jpg";
canvas.onclick = function(e) {
var x = e.pageX;
var y = e.pageY;
var canvasColor = context.getImageData(x, y, 1,1); // rgba e [0,255]
var pixels = canvasColor.data;
var r = pixels[0];
var g = pixels[1];
var b = pixels[2];
document.body.style.backgroundColor = "rgb("+r+','+g+','+b+")";
}
答案 0 :(得分:6)
尝试一下这个:
var color = document.getElementById("color");
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj, destX, destY);
};
imageObj.src = "zain.jpg";
canvas.onmousemove = function(e) {
// not so sure about these... might need to offset them or so
var x = e.x;
var y = e.y;
// set color now
var canvasColor = context.getImageData(x, y, 1, 1).data; // rgba e [0,255]
var r = canvasColor[0];
var g = canvasColor[1];
var b = canvasColor[2];
color.style.backgroundColor = 'rgb(' + r + ',' + g + ',' + b + ')';
}
请注意,该代码段要求您在某处使用ID为“color”的div。它设置了那里的像素颜色。
答案 1 :(得分:3)
您在这里寻找的是getImageData()电话。
所以,你的解决方案看起来像这样:
function getColor(canvas, x, y) {
var context = canvas.getContext("2d");
var pixel = context.getImageData(x, y, 1, 1);
// Red = rgb[0], green = rgb[1], blue = rgb[2]
// All colors are within range [0, 255]
var rgb = pixel.data;
return rgb;
}
function canvasMouseMove(e) {
var x = e.layerX, y = e.layerY;
var rgb = getColor(canvas, x, y);
var rgb_string = "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")";
document.body.style.backgroundColor = rgb_string;
}
canvas.onmousemove = canvasMouseMove;
正如@bebraw指出的那样,您可能需要根据所使用的浏览器不同地处理鼠标位置。为此,您可以考虑使用jQuery或其他JS库来简化。