思路
-
可以为canvas设置一个background的作为需要显示的目标图像,然后canvas绘制一个矩形作为遮罩层。或者通过position使用canvas覆盖在image标签上。
-
利用canvas的
globalCompositeOperation
属性可以很方便的操作绘图间的关系,详细可参考 -
因为消除后的图形为透明图形。可以使用
getImageData
抓取canvas中的图像数据来判断已消除的面积。
实现
把目标图像设置为background
this.canvas.style.background = `url(${this.CONFIG.backgroundUrl}) no-repeat center center`this.canvas.style.backgroundSize = 'cover'复制代码
绘制一个遮罩层
drawGrayMask(){ this.context.fillStyle = this.CONFIG.fillColor this.context.fillRect(0,0,this.CONFIG.width, this.CONFIG.height)}复制代码
设置绘图效果
if (this.start){ // 鼠标/手势 移动时,获取当前坐标 let x = e.touches ? e.touches[0].clientX : e.pageX let y = e.touches ? e.touches[0].clientY : e.pageY // 设置canvas属性 this.context.globalCompositeOperation = 'destination-out' this.drawLine(x, y) this.CONFIG.startX = x this.CONFIG.startY = y}复制代码
判断绘制的图像占整个canvas的比例
// 获取当前透明的面积for (let i=0; ithis.CONFIG.width*this.CONFIG.height*0.5){ this.run()}复制代码
清除整个遮罩层
clearCanvas(){ // 绘制一个面积超过canvas面积的圆 this.context.beginPath() this.context.globalCompositeOperation = 'destination-out' this.context.arc(this.CONFIG.width/2, this.CONFIG.height/2, this.CONFIG.currentRadius, 0, 2*Math.PI) this.context.fill() this.context.closePath()}update(){ if (this.CONFIG.currentRadius < this.CONFIG.width || this.CONFIG.currentRadius