这里用的requestAnimationFrame做的效果,因为他会根据你屏幕的刷新率去显示,效果比setTimeout、setInterval好
requestAnimationFrame 比起 setTimeout、setInterval的优势主要有两点:
1、requestAnimationFrame 会把每一帧中的所有DOM操作集中起来,在一次重绘或回流中就完成,并且重绘或回流的时间间隔紧紧跟随浏览器的刷新频率,一般来说,这个频率为每秒60帧。
2、在隐藏或不可见的元素中,requestAnimationFrame将不会进行重绘或回流,这当然就意味着更少的的cpu,gpu和内存使用量。
html部分代码
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="apple" />
</body>
</html>
css部分代码
body {
height: 2500vh;
background: #000;
}
canvas {
position: fixed;
max-width: 100vw;
max-height: 100vh;
}
这里图片都是在线的,如果想让效果更好,提前缓存出来所有图片,要不在滚动页面的时候可能会有空白的间隙。
获取图片的方法
const currentImg = index => (
index < 10
?
https://www.apple.com.cn/105/media/us/airpods-pro/2022/d2deeb8e-83eb-48ea-9721-f567cf0fffa8/anim/hero/large/000${index}.png
:
https://www.apple.com.cn/105/media/us/airpods-pro/2022/d2deeb8e-83eb-48ea-9721-f567cf0fffa8/anim/hero/large/00${index}.png
)
js部分代码
const html = document.documentElement;
const canvas = document.getElementById("apple");
const context = canvas.getContext("2d");
const imgCount = 65;
const currentImg = index => (
index < 10
?
`https://www.apple.com.cn/105/media/us/airpods-pro/2022/d2deeb8e-83eb-48ea-9721-f567cf0fffa8/anim/hero/large/000${index}.png`
:
`https://www.apple.com.cn/105/media/us/airpods-pro/2022/d2deeb8e-83eb-48ea-9721-f567cf0fffa8/anim/hero/large/00${index}.png`
)
const preloadImg = () => {
for (let i = 1; i < imgCount ; i++) {
const img = new Image();
img.src = currentImg(i);
}
};
const img = new Image()
img.src = currentImg(1);
canvas.width=1440;
canvas.height=810;
img.onload=function(){
context.drawImage(img, 0, 0);
}
const updateImg = index => {
context.clearRect(0, 0, canvas.width, canvas.height)
img.src = currentImg(index);
context.drawImage(img, 0, 0);
}
window.addEventListener('scroll', () => {
const scrollTop = html.scrollTop;
const maxScrollTop = html.scrollHeight - window.innerHeight;
const scrollFraction = scrollTop / maxScrollTop;
const index = Math.min(
imgCount - 1,
Math.ceil(scrollFraction * imgCount )
);
requestAnimationFrame(() => updateImg(index + 1))
});
preloadImg()
核心代码
window.addEventListener(‘scroll’, () => {
const scrollTop = html.scrollTop;
const maxScrollTop = html.scrollHeight - window.innerHeight;
const scrollFraction = scrollTop / maxScrollTop;
const index = Math.min(
imgCount - 1,
Math.ceil(scrollFraction * imgCount )
);
要算出当前滑动后是应该显示第几张图片