Reputation: 351
I have used canvas to draw black graphic using the mouse. When the mouse leaves the canvas I wanted to do some computations with the context image data, but it returns all zeros.
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);
Upvotes: 1
Views: 57
Reputation: 136638
Since you do draw black, yes, you will have only zeroes.
Transparent is 0,0,0,0
, black is 0,0,0,255
and all antialiased pixels will be 0,0,0,n
.
So yes if you read only the r,g, and b channels, you will have only zeroes.
Not sure what you want to do with this data so hard to give good advice, but one would be to take alpha channel into account (data[i+3]
), and another would be to fill your canvas with solid white instead of clearing it with transparent pixels.
Upvotes: 1