微信小程序实现刮刮乐,并计算百分比(基于uniapp)

页面

<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()
						}
				  }
				})
			}
		},

    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值