本文介绍了画布是空的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用JS使用canvas制作一张刮刮卡。我的问题是:我可以知道用户是否擦除了所有的画布?
I'm trying to make a scratch card using canvas with JS. my question is: can I know if the user have "erased" all the canvas?
我有两个图像一个在另一个,以使用户擦除顶部画布图像。
I have two images one on top the other, and I managed to make the user "erase" the on-top canvas image. I want to fire up a function when the canvas is empty\completly erased.
感谢
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);推荐答案
唯一的方法是检查canvas的imageData :
The only way is to check the imageData of the canvas :
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>
更多推荐
画布是空的吗?
发布评论