【发布时间】:2021-08-27 14:04:49
【问题描述】:
我有这部分 JavaScript 代码绘制一个条形图(比如条形图):
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerHeight / 3 * 4;
canvas.height = window.innerHeight;
const xCharCnt = window.innerHeight / 3 * 4 / 48;
const yCharCnt = window.innerHeight / 34;
const foreground1 = "#AF5BEC";
let offset = 0;
const barHeight = 20;
const speed = 4;
const limit = yCharCnt * barHeight;
let requestId = window.requestAnimationFrame(render);
function render() {
requestId = window.requestAnimationFrame(render);
// Clear screen
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw bar
ctx.fillStyle = foreground1;
ctx.fillRect(xCharCnt * 7, yCharCnt * 28, xCharCnt, -offset);
offset = offset + speed;
// Cancel animation
if (offset >= limit) window.cancelAnimationFrame(requestId);
}
问题:
a) 它是制作动画的正确方法吗?
b) 动画是否始终以相同的速度运行,无论其运行设备的分辨率如何?
【问题讨论】:
标签: javascript animation canvas