I want to develop an images sequence inside a canvas based on mouse scrollin:
when the sequence ended the canvas has to stop being fixed restoring a standard scroll
that reveils the content under the sequence, how can do that?
this is the pen
https://codepen.io/balestra78/pen/rNGqyyE
this is the code
— HTML —
<canvas id="hero-lightpass"></canvas>
<div id="lipsum">... content after sequence ...</div>
— CSS —
body {
padding: 0;
margin: 0;
}
canvas {
position: fixed;
}
#lipsum {
padding-top: 900px;
height: 200vh;
}
— JS —
const html = document.documentElement;
const canvas = document.getElementById("hero-lightpass");
const lipsum = document.getElementById("lipsum");
const context = canvas.getContext("2d");
const frameCount = 49;
const currentFrame = index => (
`https://calcionapp.it/test/AdobeStock_320972514_Video_HD_Preview${index.toString().padStart(4, '0')}.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)
}
const updateImage = index => {
img.src = currentFrame(index);
scaleToFill(img)
}
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))
if (frameIndex > 47) {
canvas.style.position = 'relative';
} else {
canvas.style.position = 'fixed';
}
});
function scaleToFill(img) {
// get the scale
var scale = Math.max(canvas.width / img.width, canvas.height / img.height);
// get the top left position of the image
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);
}
preloadImages()