用canvas画一个刮刮卡

这里是最终效果

思路

  1. 可以为canvas设置一个background的作为需要显示的目标图像,然后canvas绘制一个矩形作为遮罩层。或者通过position使用canvas覆盖在image标签上。

  2. 利用canvas的globalCompositeOperation属性可以很方便的操作绘图间的关系,详细可参考 w3school

  3. 因为消除后的图形为透明图形。可以使用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; 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
  }
}复制代码

转载于:https://juejin.im/post/5c874d03e51d455aa333e10b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值