小球类
class Ball{
constructor(obj) {
this.x = obj.x;
this.y = obj.y;
this.r = obj.r;
this.scaleX = 1;
this.scaleY = 1;
this.color = '#E685FF';
}
draw(ctx){
ctx.save();
ctx.translate(this.x, this.y);
ctx.scale(this.scaleX, this.scaleY);
ctx.beginPath();
ctx.arc(0, 0, this.r, 0, Math.PI *2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
return this;
}
}
平滑运动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
#canvas {
box-shadow: 0 0 20px #ccc;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="500"></canvas>
<script src="ball.js"></script>
<script>
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let W = canvas.width;
let H = canvas.height;
let ball = new Ball({
x: W / 2,
y: H / 2,
r: 45
}).draw(ctx);
let angle = 0;
const SWING = 160;
(function move(){
window.requestAnimationFrame(move);
ctx.clearRect(0, 0, W, H);
ball.x = W / 2 + Math.sin(angle) * SWING;
angle += 0.05;
angle %= Math.PI * 2;
ball.draw(ctx);
})()
</script>
</body>
</html>
线性运动
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let W = canvas.width;
let H = canvas.height;
let ball = new Ball({
x: 100,
y: H / 2,
r: 30
}).draw(ctx);
let angle = 0;
let vx = 2;
const SWING = 100;
(function move(){
window.requestAnimationFrame(move);
ctx.clearRect(0, 0, W, H);
ball.x += vx;
ball.y = H / 2 + Math.sin(angle) * SWING;
angle += 0.05;
angle %= Math.PI * 2;
ball.draw(ctx);
})()
脉冲运动
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let W = canvas.width;
let H = canvas.height;
let ball = new Ball({
x: W / 2,
y: H / 2,
r: 50
}).draw(ctx);
let angle = 0;
let initScale = 1;
const SWING = 0.5;
(function move(){
window.requestAnimationFrame(move);
ctx.clearRect(0, 0, W, H);
ball.scaleX = ball.scaleY = initScale + Math.sin(angle) * SWING;
angle += 0.05;
angle %= Math.PI * 2;
ball.draw(ctx);
})();