Using canvas to realize the special effect of scraping card

Canvas is widely used. It can not only be used for drawing, making tables with ECharts, but also for playing games. But this time, I will share an application of using canvas to realize the special effect of scraping card
If you don't know the basics of canvas, please read my blog The beginning and introduction of canvas

Here's the code

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no" />
		<title>use canvas Make scraping card image special effect</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");
				
				//The introduction of pictures in canvas needs to be completed after the pictures are loaded
				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;
					//Get the mouse pointer
					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;
                    //Get the mouse pointer
					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>

The picture needs to be replaced by yourself. When you open it to the web page, first press F12, and then switch to mobile device mode to see the effect!


Detailed code can access my github repository https://github.com/29DCH/Canvas-ScratchCard

Keywords: github Javascript Mobile

Added by DBookatay on Wed, 18 Dec 2019 22:32:32 +0200