canvas应用之刮刮乐实现

<!DOCTYPE html>
<html>
<head>
	<title>刮刮乐</title>
</head>
<body>
	<canvas id="can" width="500" height="500"></canvas>
	<script type="text/javascript">
		var can = document.getElementById("can");
		var ctx = can.getContext("2d");
		var wid = can.width;
		var hei = can.height;

		//当鼠标移动过快时,因为刷新率捕获事件的问题导致划过的区域并不连贯,但无法从技术层面解决,那就从视觉上入手
		var lastPoin = {} ;//上一个位置
		var nowPoin = {} ;//下一个位置

		init();
		
		function init(){
			// ctx.globalAlpha = '0.8';
			ctx.fillStyle = "#ccc";
			ctx.fillRect(0,0,wid,hei);
			ctx.globalCompositeOperation = "destination-out";//新旧像素合并


			//此处选用背景图片,因为绘制图片的话,在绘制刮刮层,图片就会被覆盖,背景图片则不会这样
			//并且图片加载是异步的,所以要等图片加载完成在设置为背景图片
			var img = new Image();
			img.src = './aa.png'; 
			img.onload = function(){
				can.style.background = "url("+ img.src +")";//背景图片

				can.addEventListener("mousedown",downFun,false);
			}
		}
		function downFun(e){
			lastPoin.x = e.clientX - can.offsetLeft;
			lastPoin.y = e.clientY - can.offsetTop;
			can.addEventListener("mousemove",moveFun,false);
			document.addEventListener("mouseup",upFun,false);
		}
		function moveFun(e){
			nowPoin.x = e.clientX - can.offsetLeft;
			nowPoin.y = e.clientY - can.offsetTop;
			ctx.beginPath();//开启新路径
			ctx.fillStyle = "rgba(1,1,1,1)";

			ctx.lineWidth = 40;
			ctx.lineCap = 'round';
			ctx.moveTo(lastPoin.x,lastPoin.y);
			ctx.lineTo(nowPoin.x,nowPoin.y);
			ctx.stroke();

			ctx.arc(nowPoin.x,nowPoin.y,20,0,Math.PI*2,0);
			ctx.closePath();
			ctx.fill();

			lastPoin.x = nowPoin.x;
			lastPoin.y = nowPoin.y;
		}
		function upFun(){
			can.removeEventListener("mousemove",moveFun,false);
			document.removeEventListener("mouseup",upFun,false);
			clearCanvas(0.7);
		}

		//计算刮开区域的占比  计算像素
		function clearCanvas(num){//当刮开区域大于一定值时,涂层全部清除
			var data = ctx.getImageData(0,0,wid,hei);
			var c = 0;
			len = data.data.length;
			for (var i = 0 ;i < len; i+=4) {
				if(data.data[i] == 0){
					c++;
				}
			}
			if(c >= len/4 * num){
				ctx.clearRect(0,0,wid,hei);
			}
		}
	</script>
</body>
</html>


猜你喜欢

转载自blog.csdn.net/qq_39403733/article/details/89212023