如何消除口吃效果?
- 画布是否只能在下一帧“就绪”时才能清除?
这个演示只在屏幕滚动时有效(所以我建议在小预览中查看)。而且,滞后问题在这里的预览中似乎没有那么严重。但是在Chrome中,图像偶尔会消失几毫秒/帧--让画布完全透明。
const html = document.documentElement;
const canvas = document.getElementById("prodPicAnimation");
const context = canvas.getContext("2d");
const frameCount = 120;
const currentFrame = index => (
`https://www.dr-adler.com/content/produkte/Sheabutter/renderAnimation/${index.toString().padStart(3, '0')}.png`
)
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=750;
canvas.height=750;
img.onload=function(){
context.drawImage(img, 0, 0);
}
const updateImage = index => {
context.clearRect(0, 0, canvas.width, canvas.height);
img.src = currentFrame(index);
context.drawImage(img, 0, 0);
}
window.addEventListener('scroll', () => {
const scrollTop = html.scrollTop;
const maxScrollTop = 750;
const scrollFraction = scrollTop / maxScrollTop;
const frameIndex = Math.min(
frameCount - 1,
Math.ceil(scrollFraction * frameCount)
);
requestAnimationFrame(() => updateImage(frameIndex + 1))
});
preloadImages()
<canvas id="prodPicAnimation"></canvas>
1条答案
按热度按时间eqfvzcg81#
我不确定这是否与
drawImage
/clearRect
的速度有关。我认为这是替换图像src
的争用条件。下面是一个没有任何滚动问题的解决方案,它预加载并预创建数组中的所有img
标记。https://codepen.io/andrewray/pen/poOwmNb?editors=1010