I have a page where a user can draw on the canvas and save the image to a file on the server. The canvas has a default black background. Is there a way to check if the user has drawn anything on the canvas before submitting the data URL representation of the image of a canvas with the toDataURL() function? So if the user doesn't draw anything on the canvas(it will be a blan开发者_运维百科k canvas with a black background), the image wont be created on the server. Should I loop through each and every pixel of the canvas to determine this? Here is what I'm doing currently:
var currentPixels = context.getImageData(0, 0, 600, 400);
for (var y = 0; y < currentPixels.height; y += 1) {
for (var x = 0; x < currentPixels.width; x += 1) {
for (var c = 0; c < 3; c += 1) {
var i = (y*currentPixels.width + x)*4 + c;
if(currentPixels.data[i]!=0)
break;
}
}
}
Assuming that something is drawn on the canvas when you click on it, you could bind a click even to the canvas that set a flag indicating that the canvas has been drawn on.
For example using jQuery:
var canvasDrawnOn = false;
$("#canvas").click(function(){
canvasDrawnOn = true;
});
I came up with this a while ago, but it doesn't suit my purposes.
First I take the image data in base64:
var imgdata = canvas.toDataURL();
Then I get an MD5 hash (I do this in PHP, but it doesn't matter; to do it in JavaScript you have to use a library, such as this) of the image data:
var h = $.md5(imgdata);
After this, you can compare the MD5 with a pre-calculated hash of an empty canvas:
if(h == EMPTYCANVAS) ...
It doesn't work for me, since the user sets the image dimensions, and different size canvases would have a different hash. Suggestions for overcoming this (while avoiding traversing pixel by pixel) would be awesome.
精彩评论