画布是空的吗?

编程入门 行业动态 更新时间:2024-10-17 07:38:10
本文介绍了画布是空的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图用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>

更多推荐

画布是空的吗?

本文发布于:2023-11-02 14:15:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552630.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:画布

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!