【发布时间】:2022-10-15 22:56:52
【问题描述】:
我在这个动画中使用canvas。动画在本地主机上运行良好,但在实时服务器上花费了太多时间。
这是因为我为这个动画使用了将近 3000 帧,所有帧都很重要。如何提高实时服务器的加载速度?
我附上了代码。如果我在某个地方错了,请检查它并帮助我。
const html = document.documentElement;
const canvas = document.getElementById("hero-lightpass");
const context = canvas.getContext("2d");
const frameCount = 2999;
const currentFrame = index => (`compressed/${index.toString().padStart(9, '720_0000')}.jpg`)
const preloadImages = () => {
for (let i = 1; i < frameCount; i++) {
const img = new Image();
img.src = currentFrame(i);
}
};
const img = new Image()
img.src = currentFrame(1);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
img.onload = function() {
scaleToFill(this);
}
function scaleToFill(img) {
var scale = Math.max(canvas.width / img.width, canvas.height / img.height);
var x = (canvas.width / 2) - (img.width / 2) * scale;
var y = (canvas.height / 2) - (img.height / 2) * scale;
context.drawImage(img, x, y, img.width * scale, img.height * scale);
}
const updateImage = index => {
img.src = currentFrame(index);
context.drawImage(img, 0, 0);
}
window.addEventListener('scroll', () => {
const scrollTop = html.scrollTop;
const maxScrollTop = html.scrollHeight - window.innerHeight;
const scrollFraction = scrollTop / maxScrollTop;
const frameIndex = Math.min(
frameCount - 1,
Math.ceil(scrollFraction * frameCount)
);
requestAnimationFrame(() => updateImage(frameIndex + 1))
});
preloadImages()
<canvas id="hero-lightpass"></canvas>
【问题讨论】:
-
您正在尝试加载三千个单独的图像,以显示一个动画?“如何提高直播服务器的加载速度?”- 通过使用视频反而 ...?
-
您可以将其转换为视频,然后使用压缩工具使其重量轻
-
这种动画有什么解决方案吗?请帮忙..
-
研究“精灵表”。
-
@RoryMcCrossan 谢谢...但实际上,我使用的是像视口这样的全尺寸图像。而且我认为精灵表仅适用于动画角色。正确的?
标签: javascript jquery canvas html5-canvas