javascript - AnimationFrames 的新手,绘制新图像时需要删除以前的图像,怎么办?
问题描述
希望你能帮助我。我是使用 AnimationFrames 的新手(开始使用以满足业务需求)。我已经设法制作了一个随着您滚动而改变的动画(通过非常有用的代码笔),但我遇到的问题是它只是添加了一个新图像,并留下了以前的图像,留下了痕迹。(可以在这里看到:https ://aimtechnologies.com/scrolltest/index )。我知道有 CancelAnimationRequest 但我不确定在哪里解决我的问题?
请参阅下面的代码:
const canvas = document.getElementById("hero-lightpass");
const context = canvas.getContext("2d");
const frameCount = 148;
const currentFrame = index => (
`images/1 & 2 Intro & Exploded View_${index.toString().padStart(5, '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=1158;
canvas.height=770;
img.onload=function(){
context.drawImage(img, 0, 0);
}
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()```
解决方案
已解决:使用 JPG 而不是 PNG
或者如果您需要使用 pngs 更改
context.drawImage(img, 0, 0);
}
``` to ```img.onload=function(){
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(img, 0, 0);
}```
推荐阅读
- python-3.x - 对数据框的行进行排序
- java - tensorflow float32的转换与java对象不兼容
- performance - 如何将 Bean shell 处理器变量传递给 jmeter 中的 HTTP 请求正文数据
- python - 分页 API 良好实践
- javascript - jQuery显示并在悬停时输入div
- c# - 将隐式强制转换的结果存储到接口中失败
- java - 如何在正方形周围移动图像
- shell - Printf 不附加到文件但 echo 吗?
- python - 在模型类上循环训练模型并按模型类更改数据框名称
- react-native - npm install -g react-native-cli - 显示错误