Home > Article > Web Front-end > Use js code to make web scratch cards
Share a piece of code for making scratch-off tickets using canvas and JS. The JS part is commented out and is less than 20 lines of code
The effect is as follows
<body> <img src="img/gailun.jpg"/> <canvas id="canvas" width="400" height="300"></canvas> </body>
There is nothing to pay special attention to. Added some CSS styles for the effect
<style type="text/css">*{margin: 0;padding: 0; }img{width: 400px;height: 300px;left: 200px;position: absolute;z-index: -1; }canvas{margin-left:200px; }</style>
1.Added
*{margin: 0;padding: 0; }
2.img in order to clear the browser’s built-in effects You need to add z-index under the gray cloth;
3. Absolute positioning of the picture
js part
Analyze the logic
1. Press the mouse to move accordingly Area scraping
2. Raise the mouse to change the mouse position without continuing to scrape
<script type="text/javascript">var canvas = document.getElementById("canvas");var context = canvas.getContext('2d');//画蒙布 context.beginPath(); context.fillStyle= 'grey' context.fillRect(0,0,400,300);//鼠标按下开刮 canvas.onmousedown=function(){ canvas.onmousemove = function(){//获取鼠标坐标var x = event.clientX;var y = event.clientY;//destination-out 显示原来的不在后来区域的部分 context.globalCompositeOperation = "destination-out"; context.beginPath(); context.arc(x-200,y,30,0,Math.PI*2); context.fill(); } }//鼠标抬起不刮开 canvas.onmouseup=function(){ canvas.onmousemove = function(){ } } </script>
It should be noted that
1. The picture and canvas are moved 200px to the left, so the starting point coordinates of the circle are reduced by 200px relative to the acquisition position;
2.globalCompositeOperation is a function of the canvas that sets or returns how to combine a source (new ) image is drawn onto the target (existing) image, and there are 10 other writing methods
The above is the detailed content of Use js code to make web scratch cards. For more information, please follow other related articles on the PHP Chinese website!