效果图:
代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>刮刮乐</title> 9 <style> 10 .canvasBox { 11 400px; 12 height: 200px; 13 margin: 100px auto; 14 } 15 16 #canvas1 { 17 background-repeat: no-repeat; 18 background-position: center; 19 background-size: 300px 180px; 20 } 21 </style> 22 </head> 23 24 <body> 25 <div class="canvasBox"> 26 <canvas width="400" height=200 id="canvas1"></canvas> 27 </div> 28 <script> 29 var oCanvas = document.getElementById('canvas1'); 30 var ctx = oCanvas.getContext('2d'); 31 var w = oCanvas.width; 32 var h = oCanvas.height; 33 var lastPoint = {}; 34 var nowPoint = {}; 35 var lastPointX, lastPointY; 36 var nowPointX, nowPointY; 37 38 function init() { 39 ctx.fillStyle = '#ccc'; 40 ctx.fillRect(0, 0, w, h); 41 42 var r = Math.random(), 43 oImg = new Image(); 44 45 if (r < 0.5) { 46 oImg.src = './1.png'; 47 } else { 48 oImg.src = './2.jpg'; 49 } 50 oImg.onload = function () { 51 oCanvas.style.backgroundImage = 'url(' + oImg.src + ')'; 52 ctx.globalCompositeOperation = 'destination-out'; 53 document.addEventListener('mousedown', downFun, false); 54 } 55 } 56 init(); 57 58 function downFun(e) { 59 lastPointX = e.clientX - oCanvas.offsetLeft; 60 lastPointY = e.clientY - oCanvas.offsetTop; 61 oCanvas.addEventListener('mousemove', moveFun, false); 62 document.addEventListener('mouseup', upFun, false); 63 } 64 65 function moveFun(e) { 66 nowPointX = e.clientX - oCanvas.offsetLeft; 67 nowPointY = e.clientY - oCanvas.offsetTop; 68 69 ctx.beginPath(); 70 ctx.fillStyle = 'transpatent'; 71 72 ctx.lineWidth = 20; 73 ctx.moveTo(lastPointX, lastPointY); 74 ctx.lineTo(nowPointX, nowPointY); 75 ctx.stroke(); 76 77 ctx.arc(nowPointX, nowPointY, 10, 0, Math.PI * 2, 0); 78 ctx.closePath(); 79 ctx.fill(); 80 81 lastPointX = nowPointX; 82 lastPointY = nowPointY; 83 } 84 85 function upFun() { 86 oCanvas.removeEventListener('mousemove', moveFun, false); 87 document.removeEventListener('mouseup', upFun, false); 88 clearAll(); 89 } 90 91 function clearAll() { 92 var d = ctx.getImageData(0, 0, w, h), 93 c = 0, 94 len = d.data.length; 95 for (var i = 0; i < len; i += 4) { 96 if (d.data[i] === 0) { 97 c++; 98 } 99 } 100 if (c > w * h * 0.7) { 101 ctx.clearRect(0, 0, w, h); 102 } 103 } 104 </script> 105 </body> 106 107 </html>
一开始鼠标滑动太快会导致两点之间产生空白,后面通过记录鼠标移动前后两点的位置,使用stroke画线即可
ctx.lineWidth = 20;
ctx.moveTo(lastPointX, lastPointY);
ctx.lineTo(nowPointX, nowPointY);
ctx.stroke();
当刮开一定的面积时就自动全部展示出来