可视化系列讲解:canvas的动画实现
warning:
这篇文章距离上次修改已过206天,其中的内容可能已经有所变动。
// 获取canvas元素并设置上下文
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 设置动画帧率
const fps = 60;
// 设置动画的相关配置
const config = {
x: 0,
y: 0,
radius: 10,
color: 'red',
speed: 1, // 每帧移动的像素数
direction: 'right' // 动画的初始移动方向
};
// 绘制动画的函数
function draw(config) {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
ctx.beginPath();
ctx.arc(config.x, config.y, config.radius, 0, 2 * Math.PI); // 绘制圆形
ctx.fillStyle = config.color;
ctx.fill();
}
// 更新动画配置的函数
function update(config) {
if (config.direction === 'right') {
config.x += config.speed;
if (config.x >= canvas.width - config.radius) {
config.direction = 'down';
}
} else if (config.direction === 'down') {
config.y += config.speed;
if (config.y >= canvas.height - config.radius) {
config.direction = 'left';
}
} else if (config.direction === 'left') {
config.x -= config.speed;
if (config.x <= config.radius) {
config.direction = 'up';
}
} else if (config.direction === 'up') {
config.y -= config.speed;
if (config.y <= config.radius) {
config.direction = 'right';
}
}
}
// 运行动画
function run() {
update(config);
draw(config);
setTimeout(run, 1000 / fps); // 使用setTimeout来控制帧率
}
run(); // 开始动画
这段代码使用了setTimeout来实现循环动画,通过修改config对象中的x和y值,实现小圆点在canvas上不断移动,并且会在碰到边界时改变移动方向。这个简单的例子展示了如何使用JavaScript和HTML canvas元素创建基本的动画效果。
评论已关闭