用canvas实现刮刮卡特效

版权声明:个人博客网址 https://29dch.github.io/ 博主GitHub网址 https://github.com/29DCH,欢迎大家前来交流探讨和fork! https://blog.csdn.net/CowBoySoBusy/article/details/82966836

canvas(画布)应用十分广泛,不仅可用来画图,配合ECharts做表格,还能做游戏.不过这次分享一下用canvas实现刮刮卡特效的一个应用.
如果还不是很了解canvas基本知识,可以读一下我的相关博客 canvas初识与入门

这里直接上代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no" />
		<title>用canvas做刮刮卡图片特效</title>
		<style type="text/css">
			*{
				margin: 0;
				padding: 0;
			}
			html,body{
				height: 100%;
				overflow: hidden;
			}
			#wrap{
				height: 100%;
				overflow: hidden;
			}
			#wrap > div{
				height: 100%;
				background: url(img/o_neo.jpg) no-repeat;
				background-size:100% 100% ;
			}
			canvas{
				position: absolute;
				left: 0;
				top: 0;
			}
		</style>
	</head>
	<body>
		<div id="wrap">
			<div></div>
			<canvas></canvas>
		</div>
	</body>
	<script type="text/javascript">
		window.onload=function(){
			var canvas =document.querySelector("canvas");
			canvas.width = document.documentElement.clientWidth;
			canvas.height = document.documentElement.clientHeight;
			
			if(canvas.getContext){
				var ctx = canvas.getContext("2d");
				
				//在canvas中引入图片,需要在图片加载完成之后
				var img = new Image();
				img.src="img/cover.jpeg";
				img.onload=function(){
					draw();
				}
			}
			
			function draw(){
				ctx.drawImage(img,0,0,canvas.width,canvas.height );
				canvas.addEventListener("touchstart",function(ev){
					ev = ev||event;
					//拿到鼠标指针
					var touchC = ev.changedTouches[0];
					var x = touchC.clientX ;
					var y = touchC.clientY ;
					ctx.save();
					ctx.beginPath();
					ctx.globalCompositeOperation="destination-out";
					ctx.arc(x,y ,20,0,360*Math.PI/180);
					ctx.fill();
					ctx.restore();
				})

				canvas.addEventListener("touchmove",function(ev){
					ev = ev||event;
                    //拿到鼠标指针
					var touchC = ev.changedTouches[0];
					var x = touchC.clientX ;
					var y = touchC.clientY ;
					ctx.save();
					ctx.beginPath();
					ctx.globalCompositeOperation="destination-out";
					ctx.arc(x,y ,20,0,360*Math.PI/180);
					ctx.fill();
					ctx.restore();
				})
			}
		}
	</script>
</html>

图片需要自己替换,打开到网页上时要先按F12,然后切换到移动设备模式才能看到效果!
在这里插入图片描述
在这里插入图片描述
详细代码可以访问我的github仓库 https://github.com/29DCH/Canvas-ScratchCard

猜你喜欢

转载自blog.csdn.net/CowBoySoBusy/article/details/82966836