<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>刮刮乐</title> </head> <body> <canvas>你的浏览器不支持canvas标签</canvas> <script> var arr=['img/1.jpg','img/2.jpg']; var flag=0; var obj=[]; //图片预加载 for(var i=0;i<2;i++) { var img=new Image(); img.src=arr[i]; obj[i]=img; img.onload=function() { flag++; if(flag==arr.length) { callback(obj); } } } function callback(obj) { var mycanvas=document.querySelector('canvas'); //10%的中奖率 var num=Math.ceil(Math.random()*10); if(num==8) { mycanvas.style.background='url('+arr[1]+')'; }else { mycanvas.style.background='url('+arr[0]+')'; } //绘制一个遮盖层 var ctx=mycanvas.getContext("2d"); ctx.fillStyle='#ccc'; ctx.fillRect(0,0,mycanvas.width,mycanvas.height); //刮开效果 mycanvas.onmousedown=function() { mycanvas.onmousemove=function(e) { e=e||window.event; var mouseX=e.offsetX; var mouseY=e.offsetY; ctx.clearRect(mouseX,mouseY,10,10); } } mycanvas.onmouseup=document.onmouseup=function() { mycanvas.onmousemove=null; } } </script> </body> </html>