ES6 and canvas implement the following effect on the mouse ball and es6canvas ball
Recently, I was bored. I read ES6 syntax and used canvas to implement animation effects. As the mouse moves, there will be an animation where the ball follows and disappears automatically.
First, the html part is currently a canvas tag.
1 <canvas id = "canvas"> 2. The current browser does not support this function! 3 </canvas>
Secondly, the css section does not consider appearance. If you like it, you can add your own style.
1 <style>2 body{3 margin: 90px;4 }5 #canvas{6 box-shadow: 0 0 5px;7 }8 </style>
Finally, let's look at the js implementation section.
1 <script> 2 const canvas = document. getElementById ("canvas"); 3 canvas. height = 600; 4 canvas. width = 1000; 5 canvas. style. backgroundColor = "#000"; 6 const ctx = canvas. getContext ("2d"); 7 8 // Ball 9 class Ball {10 constructor (x, y, color) {11 this. x = x; 12 this. y = y; 13 this. color = color; 14 // the radius of the ball is 4015 by default. this. r = 40; 16} 17 // draw the ball 18 render () {19 ctx. save (); 20 ctx. beginPath (); 21 ctx. arc (this. x, this. y, this. r, 0, Math. PI * 2); 22 ctx. fillStyle = this. color; 23 ctx. fill (); 24 ctx. restore (); 25} 26} 27 // mobile Ball 28 class MoveBall extends Ball {29 constructor (x, y, color) {30 super (x, y, color ); 31 32 this. dX = Math. floor (Math. random () * 5 + 1); 33 this. dY = Math. floor (Math. random () * 5 + 1); 34 this. dR = Math. floor (Math. random () * 5 + 1); 35} 36 37 upData () {38 this. x + = this. dX; 39 this. y + = this. dY; 40 this. r-= this. dR; 41 if (this. r <0) {42 this. r = 0; 43} 44} 45} 46 47 let ballArry = []; 48 let colorArry = ['red', 'green', 'pink ', 'yellow ', 'Blue ']; 49 50 canvas. addEventListener ("mousemove", function (e) {51 ballArry. push (new MoveBall (e. offsetX, e. offsetY, colorArry [Math. floor (Math. random () * 5)]); 52}) 53 54 setInterval (function () {55 ctx. clearRect (0, 0, canvas. width, canvas. height); 56 57 for (let I = 0; I <ballArry. length; I ++) {58 ballArry [I]. render (); 59 ballArry [I]. upData (); 60} 61}, 50); 62 </script>
I will briefly explain my design ideas:
First, get the canvas object, get the context, and set some basic attributes. (Canvas is not described too much. You can go to w3 to study it yourself ). Then, define a Ball class, which contains the coordinates of the center of the Ball, and the radius and color. When defining a small ball painting method, you can go to the canvas document to view the specific circle implementation.
Define a small Ball and inherit the Ball class. There will be a method to update the ball status, used to change the ball's radius and color.
Finally, enable a timer. When the mouse moves, store the generated ball in the array, traverse the loop to read the ball, and change the style of the ball to achieve the final effect.
Complete code is attached. Directly copy the browser to run.
1 <! DOCTYPE html> 2