<!DOCTYPE html>
<html><head><meta charset="UTF-8"><style>* {margin: 0;padding: 0;}#myCanvas {cursor: pointer;margin:50px 400px;box-shadow: 6px 9px 80px 13px rgba(0,0,0,.65);transition:all 1s linear;}img{position:absolute;top:50px;left:400px;width: 500px;height: 500px;z-index:-10;}</style><title>刮刮乐</title></head><body><img src="img/1.jpg"><canvas id="myCanvas" width="500" height="500"></canvas></body><script src="js/jquery-2.2.4.min.js"></script><script src="js/guaguale.js"></script>
</html>
JS版
var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");ctx.fillStyle = "lightgray";
ctx.fillRect(0,0,500,500);ctx.globalCompositeOperation = "destination-out";myCanvas.onmousedown = function(e){myCanvas.onmousemove = function(e){var even = e || event;var x = even.clientX-400;var y = even.clientY-50;ctx.beginPath();ctx.arc(x,y,20,0,Math.PI*2,false);ctx.closePath();ctx.fillStyle = "rgba(0,0,0,1)";ctx.fill();adjustPrefix();}
}
function adjustPrefix(){var imagePoints = ctx.getImageData(0,0,myCanvas.width,myCanvas.height);var count = 0;var datas = imagePoints.data;for(var i = 0;i < datas.length;i+=4){if(datas[i+3] == 0){count++;}if(2*count >= datas.length/4){myCanvas.style.opacity = 0;}}
}document.onmouseup = function(){myCanvas.onmousemove = null;
}
JQ版
$(window).on("load", function () {ctx.fillStyle = "lightgray";ctx.fillRect(0, 0, myCanvas.width, myCanvas.height);ctx.globalCompositeOperation = "destination-out";$("#myCanvas").on("mousedown", function () {$(document).on("mousemove", function (e) {var centerX = e.pageX - $("#myCanvas").offset().left;var centerY = e.pageY - $("#myCanvas").offset().top;ctx.beginPath();ctx.arc(centerX, centerY, 20, 0, Math.PI * 2, false);ctx.closePath();ctx.fillStyle = "red";ctx.fill();adjustPrefix();});})function adjustPrefix() {var imagePoints = ctx.getImageData(0, 0, myCanvas.width, myCanvas.height);var count = 0;var datas = imagePoints.data;for (var i = 0; i < datas.length; i += 4) {if (datas[i + 3] == 0) {count++;}if (2 * count >= datas.length / 4) {myCanvas.style.opacity = 0;}}}$(document).on("mouseup", function () {$(document).off("mousemove");});
});