页面
<canvas
canvas-id="canvas"
id="canvas"
class="canvas"
:style="{
backgroundImage: `url(${canvasBackgroundImage})`,
}"
@touchstart.stop="handleCanvasTouchStart"
@touchmove.stop="handleCanvasTouchMove"
@touchend.stop="handleCanvasTouchEnd"
></canvas>
JS
onShow() {
this.initCanvas()
},
onHide() {
this.clearTimer()
},
onUnload() {
this.clearTimer()
},
methods: {
clearTimer() {
clearTimeout(this.intervalTime)
this.intervalTime = null
},
initCanvas() {
this.ctx = uni.createCanvasContext('canvas')
setTimeout(() => {
uni.createSelectorQuery().select('#canvas').boundingClientRect().exec(res => {
this.canvasW = res[0].width
this.canvasH = res[0].height
this.canvasTop = res[0].top
this.canvasLeft = res[0].left
uni.downloadFile({
url: 'https://image.51cheyaoshi.com/xcx/app/static/partner/prize-mask.png',
success: (imgRes) => {
this.ctx.drawImage(imgRes.tempFilePath, 0, 0, this.canvasW, this.canvasH)
this.ctx.draw()
this.canvasBackgroundImage = 'https://image.51cheyaoshi.com/xcx/app/static/partner/prize1.png'
},
})
})
})
},
handleCanvasTouchStart(e) {
this.status = true
},
handleCanvasTouchMove(e) {
if (this.status) {
const x = e.changedTouches[0].pageX - this.canvasLeft
const y = e.changedTouches[0].pageY - this.canvasTop
this.ctx.clearRect(x-this.r/2, y-this.r/2, this.r, this.r)
this.ctx.draw(true, () => {
if (!this.intervalTime) {
this.intervalTime = setInterval(() => {
this.getFilledPercentage()
this.clearTimer()
}, 200)
}
})
}
},
handleCanvasTouchEnd(e) {
this.status = false
},
getFilledPercentage() {
if (this.status) {
uni.canvasGetImageData({
canvasId: 'canvas',
x: 0,
y: 0,
width: this.canvasW,
height: this.canvasH,
success: (imgData) => {
// imgData.data是个数组,存储着指定区域每个像素点的信息,数组中4个元素表示一个像素点的rgba值
const pixels = imgData.data
const transPixels = []
for (let i = 0; i < pixels.length; i += 4) {
// 严格上来说,判断像素点是否透明需要判断该像素点的a值是否等于0,
// 为了提高计算效率,这儿设置当a值小于128,也就是半透明状态时就可以了
if (pixels[i + 3] < 128) {
transPixels.push(pixels[i + 3])
}
}
const rate = (transPixels.length / (pixels.length / 4) * 100).toFixed(2)
if (rate > 60) {
this.ctx.clearRect(0, 0, this.canvasW, this.canvasH)
this.clearTimer()
}
}
})
}
},
}