這裏是最終效果canvas
能夠爲canvas設置一個background的做爲須要顯示的目標圖像,而後canvas繪製一個矩形做爲遮罩層。或者經過position使用canvas覆蓋在image標籤上。this
利用canvas的globalCompositeOperation
屬性能夠很方便的操做繪圖間的關係,詳細可參考 w3schoolurl
由於消除後的圖形爲透明圖形。能夠使用getImageData
抓取canvas中的圖像數據來判斷已消除的面積。spa
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
}
複製代碼
// 獲取當前透明的面積
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
}
}複製代碼