gpt4 book ai didi

javascript - Canvas 上下文返回零

转载 作者:行者123 更新时间:2023-11-30 19:55:27 25 4
gpt4 key购买 nike

我用 Canvas 用鼠标绘制黑色图形。当鼠标离开 Canvas 时,我想对上下文图像数据进行一些计算,但它返回全零。

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,0,0,0,黑色为 0,0,0,255,所有抗锯齿像素为 0,0,0,n

所以是的,如果您只读取 r、g 和 b channel ,您将只有零。

不确定你想用这些数据做什么很难给出好的建议,但一个是考虑 alpha channel (data[i+3]),另一个是用纯白色填充 Canvas ,而不是用透明像素清除 Canvas 。

关于javascript - Canvas 上下文返回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54048135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com