我试图使用带有JS的画布制作刮刮卡。我的问题是: 我可以知道用户是否已经删除了#34;所有画布?
我有两个图像一个在另一个上面,我设法让用户"擦除"顶部的画布图像。我想在画布为空\完全擦除时启动一个函数。
由于
var offsetT;
var offsetL;
var canvas = document.createElement('canvas');
canvas.id = "canvas";
var canvasWidth = 290;
var canvasheight = 269;
canvas.width = canvasWidth;
canvas.height = canvasheight;
var context = canvas.getContext("2d");
var scratcher = document.getElementById("scratcher");
var radius = 20; //Brush Radius
context.drawImage(scratcher,0,0);
// set image as pattern for fillStyle
context.globalCompositeOperation = 'destination-out';
context.fillStyle = context.createPattern(scratcher, "repeat");
// for demo only, reveals image while mousing over canvas
canvas.onmousemove = function (e) {
var r = this.getBoundingClientRect(),
x = e.clientX - r.left,
y = e.clientY - r.top;
context.beginPath();
context.moveTo(x + radius, y);
context.arc(x, y, radius, 0, 2 * Math.PI);
context.fill();
};
document.body.appendChild(canvas);
document.addEventListener('touchmove', function(e){
var touchobj = e.changedTouches[0]; // reference first touch point (ie: first finger)
var x = touchobj.clientX;
var y = touchobj.clientY;
offsetT = canvas.offsetTop;
offsetL = canvas.offsetLeft;
context.beginPath();
context.moveTo(x-offsetL + radius, y-offsetT);
context.arc(x-offsetL,y-offsetT, radius, 0, 2 * Math.PI);
context.fill();
var cursor = document.getElementById('cursor');
cursor.style.display = 'block';
cursor.style.left = x+ "px";
cursor.style.top = y+ "px";
e.preventDefault();
}, false);
答案 0 :(得分:1)
唯一的方法是检查画布的imageData:
var data = ctx.getImageData(0,0,ctx.canvas.width, ctx.canvas.height).data;
var isEmpty = !Array.prototype.some.call(data, function(p){return p>0;});
var ctx = c.getContext('2d');
var isEmpty = function(ctx){
var data = ctx.getImageData(0,0,ctx.canvas.width, ctx.canvas.height).data;
return !Array.prototype.some.call(data, function(p){return p>0;});
}
//first check before drawing
log.innerHTML += isEmpty(ctx)+' ';
//no more empty
ctx.fillRect(0,0,10,10);
// recheck
log.innerHTML += isEmpty(ctx);
/*
we could also have used a for loop :
//in Function
for(var i=0; i<data.length; i++){
if(data[i]>0){
return false;
}
return true;
}
*/
<canvas id="c"></canvas>
<p id="log"></p>