用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
  }
}複製代碼
相關文章
相關標籤/搜索