其他分享
首页 > 其他分享> > canvas_07 炫彩小球

canvas_07 炫彩小球

作者:互联网

效果图:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4     <head>
 5         <meta charset="UTF-8">
 6         <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7         <meta name="viewport" content="width=device-width, initial-scale=1.0">
 8         <title>Canvas</title>
 9         <style>
10             * {
11                 margin: 0;
12                 padding: 0;
13             }
14         </style>
15     </head>
16 
17     <body>
18         <canvas id="canvas"></canvas>
19 
20         <script>
21             var canvas = document.querySelector("#canvas");
22             var ctx = canvas.getContext("2d");
23             // -6是滚动条
24             var w = document.documentElement.clientWidth - 6;
25             var h = document.documentElement.clientHeight - 6;
26             canvas.width = w;
27             canvas.height = h;
28 
29             function randNum(num) {
30                 return Math.random() * num;
31             }
32 
33             function drawCricle(x, y, r, color) {
34                 ctx.beginPath();
35                 ctx.arc(x, y, r, 0, Math.PI * 2);
36                 ctx.fillStyle = color || "#000";
37                 ctx.fill();
38             }
39 
40             function Ball(x, y) {
41                 this.x = x;
42                 this.y = y;
43                 this.r = 60;
44                 this.color = "rgb(" + parseInt(Math.random() * 255) +
45                     "," + parseInt(Math.random() * 255) +
46                     "," + parseInt(Math.random() * 255) + ")";
47             }
48 
49             Ball.prototype.show = function() {
50                 this.r--;
51                 drawCricle(this.x, this.y, this.r, this.color);
52             }
53 
54             function animation() {
55                 var ballArr = [];
56                 window.onmousemove = function(e) {
57                     var ball = new Ball(e.x, e.y);
58                     ballArr.push(ball);
59                     ball.show();
60                 }
61 
62                 setInterval(() => {
63                     ctx.clearRect(0, 0, w, h);
64                     for (var i = 0; i < ballArr.length; i++) {
65                         var ball = ballArr[i];
66                         if (ball.r <= 0) {
67                             ballArr.splice(i, 1);
68                         } else {
69                             ball.show();
70                         }
71                     }
72                 }, 10);
73             }
74 
75             animation();
76         </script>
77     </body>
78 
79 </html>

 

标签:function,canvas,ball,07,炫彩,ctx,var,Math
来源: https://www.cnblogs.com/luwei0915/p/15734747.html