1. 程式人生 > >躁動的小球特效

躁動的小球特效

col ext pan 特效 func rec tle fill idt

原生js制作(es6)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #myCanvas{
                border: 1px solid red;
            }
        </style>
    </head>
    <body
> <canvas id="myCanvas" width="500" height="300"></canvas> <script> var rand = (min,max) => parseInt(Math.random()*(max-min)+min); var myCanvas = document.querySelector(#myCanvas); var ctx = myCanvas.getContext(
2d); const canvasWidth = myCanvas.width; const canvasHeigh = myCanvas.height; class Ball{ constructor(ctx,canvasWidth,canvasHeigh){ this.ctx = ctx; // 顏色 this.color
= `rgb(${rand(1,256)},${rand(1,256)},${rand(1,256)})`; // 半徑 var r = rand(2,10); this.r = r; // 坐標 this.x = rand(r,canvasWidth-r); this.y = rand(r,canvasHeigh-r); // 可移動的峰值 this.maxWidth = canvasWidth - r; this.maxHeight = canvasHeigh - r; // 速度 var speedX = rand(1,3); this.speedX = rand(0,2) > 0 ? speedX : -speedX; var speedY = rand(1,3); this.speedY = rand(0,2) > 0 ? speedY : -speedY; } draw(){ this.ctx.beginPath(); this.ctx.fillStyle = this.color; this.ctx.arc(this.x,this.y,this.r,0,Math.PI*2,true); this.ctx.closePath(); this.ctx.fill(); } move(){ this.x += this.speedX; if(this.x >= this.maxWidth){ this.speedX *= -1; }else if(this.x < this.r){ this.speedX *= -1; } this.y += this.speedY; if(this.y >= this.maxHeight){ this.speedY *= -1; }else if(this.y < this.r){ this.speedY *= -1; } } } var balls = []; for(let i=0;i<100;i++){ var ball = new Ball(ctx,canvasWidth,canvasHeigh); balls.push(ball); } setInterval(function(){ ctx.clearRect(0,0,canvasWidth,canvasHeigh) for(let key in balls){ var ball = balls[key]; ball.draw(); ball.move(); } },30) </script> </body> </html>

躁動的小球特效