canvas高级动画示例
演示地址 https://qzruncode.github.io/example/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="500px" height="500px"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
var cRect = canvas.getBoundingClientRect();
var raf;
var running = false;
var ball = {
x: 100,
y: 100,
vx: 5,
vy: 2,
radius: 25,
color: 'red',
draw: function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
};
function clear() {
// ctx.clearRect(0, 0, canvas.width, canvas.height);
// 尾影效果使用下面
ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function draw() {
clear();
ball.draw();
// 移动
ball.x += ball.vx;
ball.y += ball.vy;
// 曲线运动
ball.vy *= .99;
ball.vy += .25;
// 边界
if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
ball.vy = -ball.vy;
}
if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
ball.vx = -ball.vx;
}
raf = window.requestAnimationFrame(draw);
}
canvas.addEventListener('mousemove', function (e) {
if (!running) {
clear();
ball.x = Math.round(e.clientX - cRect.left);
ball.y = Math.round(e.clientY - cRect.top);
ball.draw(); // 直接调用draw只会绘制一帧
}
});
canvas.addEventListener('click', function (e) {
if (!running) {
raf = window.requestAnimationFrame(draw);
running = true;
}
});
canvas.addEventListener('mouseout', function (e) {
window.cancelAnimationFrame(raf);
running = false;
});
ball.draw();
</script>
</body>
</html>