用canvas画一个刮刮卡

这里是最终效果canvas

思路

  1. 能够为canvas设置一个background的做为须要显示的目标图像,而后canvas绘制一个矩形做为遮罩层。或者经过position使用canvas覆盖在image标签上。this

  2. 利用canvas的globalCompositeOperation属性能够很方便的操做绘图间的关系,详细可参考 w3schoolurl

  3. 由于消除后的图形为透明图形。能够使用getImageData抓取canvas中的图像数据来判断已消除的面积。spa

实现

把目标图像设置为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; i<datas.length-3; i+=4){
  if (datas[i] === 0 && datas[i+1] === 0 && datas[i+2] === 0 && datas[i+3] === 0){
    transparent++
  }
}

// 当透明面积超过总面积50%,清除全部的遮罩层
if(transparent > this.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<this.CONFIG.height){
    this.CONFIG.currentRadius *= this.CONFIG.clearSpeed
  }
}复制代码
相关文章
相关标签/搜索