<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"> <title></title> </head> <style type="text/css"> *{ margin: 0; padding: 0; } img{ 80%; height: 80%; } html,body{ 100%; height: 100%; overflow: hidden; } div{ 100%; height: 100%; overflow: hidden; } canvas{ margin: 0 auto; display: block; } </style> <body> <div class="box"> <canvas id="game"></canvas> </div> </body> <script type="text/javascript"> function ggl(){ //创建画布 var game = document.getElementById('game'); var obj = game.getContext('2d'); //创建图片 var imgs = ['images/1.png','images/2.png','images/3.png','images/4.png','images/6.png','images/7.png']; //图片随机 var img = imgs[Math.floor(Math.random()*imgs.length)]; var pic= new Image; pic.src = img; pic.onload = function(){ game.width = this.width; game.height = this.height; game.style.background = 'url('+this.src+')'; //填充灰色矩形 obj.fillStyle = 'gray'; obj.fillRect(0,0,this.width,this.height); //核心代码 让图层可以覆盖叠加 obj.globalCompositeOperation = 'destination-out'; console.log('图片加载完成'); //声明鼠标按下开关 var off = 0; var startX = 0; var startY = 0; //鼠标的位置 game.addEventListener('touchstart',function(e){ off = 1; startX = this.offsetLeft; startY = this.offsetTop; // console.log(startX); }); //抬起鼠标关闭 game.addEventListener('touchend',function(e){ // console.log(z轴动); off = 0; }); //鼠标移动 game.addEventListener('touchmove',function(e){ var e=e||window.event; // console.log(e.touches[0].pageX) if(!off) return; var x = e.touches[0].pageX - startX; var y = e.touches[0].pageY - startY; //绘制个圆形 obj.beginPath(); obj.fillStyle = 'rgba(0,0,0,0.1)'; obj.arc(x,y,30,0,2*Math.PI); obj.fill(); // console.log(x); }) }; console.log(img) } ggl(); </script> </html>