canvas实现刮刮卡效果
canvas实现刮刮卡效果
实现步骤:
- 设置页面背景图,即刮刮卡底部图片
- 绘制canvas 刮刮卡顶部图片drawImage
- 绑定事件 addEventListener touchstart、touchmove
完整代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"> 6 <title>02</title> 7 <style type="text/css"> 8 * { 9 padding: 0; 10 margin: 0; 11 } 12 html, body { 13 height: 100%; 14 overflow: hidden; 15 } 16 #wrap { 17 height: 100%; 18 overflow: hidden; 19 } 20 #wrap > div { 21 height: 100%; 22 background-image: url(1.jpg); 23 background-repeat: no-repeat; 24 background-size: 100% 100%; 25 } 26 canvas { 27 position: absolute; 28 left: 0; 29 top: 0; 30 } 31 </style> 32 </head> 33 <body> 34 <div id="wrap"> 35 <div></div> 36 <canvas></canvas> 37 </div> 38 <script type="text/javascript"> 39 window.onload = function(){ 40 var canvas = document.querySelector("canvas"); 41 canvas.width = document.documentElement.clientWidth; 42 canvas.height = document.documentElement.clientHeight; 43 if(canvas.getContext){ 44 var ctx = canvas.getContext("2d"); 45 var img = new Image(); 46 img.src = "2.jpg"; 47 img.onload = function(){ 48 ctx.drawImage(img, 0, 0, canvas.width, canvas.height); 49 canvas.addEventListener("touchstart", function(ev){ 50 ev = ev || event; 51 var touchC = ev.changedTouches[0]; 52 var x = touchC.clientX; 53 var y = touchC.clientY; 54 ctx.save(); 55 ctx.beginPath(); 56 ctx.globalCompositeOperation = "destination-out"; 57 ctx.arc(x,y,25,0,360*Math.PI/180); 58 ctx.fill(); 59 ctx.restore(); 60 }) 61 62 canvas.addEventListener("touchmove", function(ev){ 63 ev = ev || event; 64 var touchC = ev.changedTouches[0]; 65 var x = touchC.clientX; 66 var y = touchC.clientY; 67 ctx.save(); 68 ctx.beginPath(); 69 ctx.globalCompositeOperation = "destination-out"; 70 ctx.arc(x,y,25,0,360*Math.PI/180); 71 ctx.fill(); 72 ctx.restore(); 73 }) 74 } 75 } 76 77 } 78 </script> 79 </body> 80 </html>
底图:
效果如下: