Share a piece of code with canvas and JS to make scratch music, JS section to remove comments less than 20 lines of code
The effect is as follows
Galen jpg
Scraping music. Gifhtml part
<body> ![](img/gailun.jpg) <canvas id="canvas" width="400" height="300"></canvas> </body>
There's nothing special to pay attention to.
Add some CSS styles to the effect
CSS Section
<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>
Attention
1. In order to clear the browser comes with the effect of adding
*{ margin: 0; padding: 0; }
2.img needs to be under the gray cloth, add the z-index;
3. Image absolute Positioning
JS section
Analyze the logic below
1. Press the mouse button to move the corresponding area to scrape open
2. Mouse lift to change the position of the mouse does not continue to scrape open
JS Code
<ScriptType="Text/javascript" > var canvas =document.getElementById ("Canvas");var context = Canvas.getcontext (' 2d ');Painting Context.beginpath (); context.fillstyle=' Grey ' context.fillrect (0,0,400,300);Mouse Press to open the scratch canvas.onmousedown=function) {Canvas.onmousemove =function//get mouse coordinates var x = Event.clientX; Span class= "Hljs-keyword" >var y = event.clienty; //destination-out show the original part of the area not later context.globalcompositeoperation = "Destination-out"; Context.beginpath (); Context.arc (X-200,y, 30,0,Math.PI* 2); Context.fill (); }} //mouse lift does not scrape open Canvas.onmouseup= function ( function () {}} </ SCRIPT>
It is important to note that
1. The picture and canvas shifted left 200px, so the starting coordinates of the circle were reduced by 200px relative to the acquiring position;
2.globalCompositeOperation is a function of the canvas is to set or return how to draw a source (new) image to the target (existing) image, as well as the remaining 10 kinds of wording
You are welcome to join the Learning Exchange Group if you encounter any problems or want to acquire learning resources in the learning process.
343599877, we learn the front-end together!
20 Line JS code making web scraping music