uniApp开发教程之uniApp实现刮刮奖效果
uniApp实现刮刮奖效果代码
<template> <view> <div style="background-color: red; padding: 40px;"> <div style="position: relative;"> <div id="gift" class="gift">恭喜,您获得了华为手机</div> <canvas class="canvas" @touchstart="start" @touchend="end" @touchmove="move" canvas-id="firstCanvas"></canvas> </div> </div> </view> </template> <script> var ctx; var sx = 0, sy = 0, perNum = 0; var giftWidth=0,giftHeight=0; var canvasId = "firstCanvas"; export default { data: function() { return { w: 200, h: 100, isfinish:false, isClear:false } }, onReady: function() { this.createCtx(); this.giftWidth(); }, methods: { giftWidth:function(){ const query = uni.createSelectorQuery().in(this); query.select('#gift').boundingClientRect(data => { giftWidth=data.width; giftHeight=data.height; }).exec(); }, finish:function(){ this.isfinish=true; }, done:function(){ uni.showToast({ title:"恭喜你中奖了" }); }, start: function(e) { if(this.isfinish){ if(!this.isClear){ this.isClear=true; this.done(); ctx.moveTo(0, 0); ctx.clearRect(0,0, 200, 100); ctx.stroke() ctx.draw(true); } return false; } sx = e.touches[0].x; sy = e.touches[0].y; console.log(e.touches[0].x + " " + e.touches[0].y) this.getFilledPercentage(); }, end: function(e) { if(this.isfinish) return false; }, move: function(e) { if(this.isfinish){ if(!this.isClear){ this.isClear=true; this.done(); ctx.moveTo(0, 0); ctx.clearRect(0,0, 200, 100); ctx.stroke() ctx.draw(true); } return false; } ctx.moveTo(sx, sy); ctx.clearRect(sx, sy, 10, 10) ctx.stroke() ctx.globalAlpha = 0; ctx.draw(true); this.getFilledPercentage(); sx = e.touches[0].x; sy = e.touches[0].y; }, createCtx: function() { ctx = uni.createCanvasContext(canvasId); this.createRect(); }, createRect: function() { ctx.setFillStyle('#646464') ctx.fillRect(0, 0, 300, 200); ctx.draw(true) }, getFilledPercentage: function() { var that=this; uni.canvasGetImageData({ canvasId: canvasId, x: (that.w-giftWidth)/2-5, y: (that.h-giftHeight)/2-5, width: giftWidth, height: giftHeight, success: function(res) { let pixels = res.data; let transPixels = []; for (let i = 0; i < pixels.length; i += 4) { if (pixels[i + 3] < 128) { transPixels.push(pixels[i + 3]); } } perNum = (transPixels.length / (pixels.length / 4) * 100).toFixed(2); if(perNum>=60){ console.log("finish"); that.finish();; } console.log(perNum) } }); } } } </script> <style> .gift { position: absolute; left: 50%; top: 50%; margin-left: -100px; margin-top: -16px; font-size: 16px; border:1px solid #eee; padding:10px; border-radius:10px; box-sizing:border-box; text-align:center; } .canvas{ width: 200px; height: 100px; margin: 0 auto; } </style>