我已经使用画布使用鼠标绘制黑色图形。当鼠标离开画布时,我想对上下文图像数据进行一些计算,但是它将返回全零。
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
canvas.style = "border:5px solid gray"
var drawable = canvas.getContext("2d");
document.body.appendChild(canvas);
var clicked = false;
canvas.addEventListener('mousedown', function() {
clicked = true;
}, false);
canvas.addEventListener('mouseup', function() {
clicked = false;
}, false);
canvas.addEventListener('mouseleave', function() {
var data = drawable.getImageData(0, 0, 100, 100).data;
var inputs = [];
for (var i = 0, n = data.length; i < n; i += 4) {
var red = data[i];
var green = data[i + 1];
var blue = data[i + 2];
var gray = (red + green + blue) / 3;
console.log(red + "-" + green + "-" + blue + "-" + gray);
}
drawable.clearRect(0, 0, 100, 100);
clicked = false;
}, false);
canvas.addEventListener('mousemove', function(event) {
var x = event.clientX;
var y = event.clientY;
if (clicked) {
drawable.arc(x, y, 5, 0, 2 * Math.PI);
drawable.closePath();
drawable.fill();
drawable.beginPath();
}
}, false);
答案 0 :(得分:1)
因为您确实绘制了黑色,是的,您将只有零。
透明为0,0,0,0
,黑色为0,0,0,255
,所有抗锯齿像素均为0,0,0,n
。
是的,如果您仅读取r,g和b通道,则将只有零。
不确定要如何处理这些数据,以至于难以给出好的建议,但是一种方法是考虑alpha通道(data[i+3]
),另一种方法是用纯白色填充画布用透明像素清除它。