Question:
How to make custom element interact with the browser scroll?
Product:
Wix Editor
What are you trying to achieve:
I have created a custom Element that changes images based on browser scroll, the images are changing but the getBoundingClient() for the custom element is not working as expected, help would be appreciated
What have you already tried:
I have tried referencing the custom element as this.getBoundingClientRect() but it’s not working as expected
Additional information:
Here’s the code: Please note that this is a custom element code and the custom element is used on a page of wix editor
const init = () => {
preloadImages(images, () => {
// const height = calHeight(images, this.frequency);
imageSequenceContainer.style.height = `100vh`;
// heightDiv.style.height = `${height}px`;
// window.addEventListener('wheel', throttle(onScroll, 50));
window.addEventListener('wheel', onScroll);
drawImage(loadedImages[0]);
});
};
const onScroll = () => {
changeImage();
};
const changeImage = () => {
// const coordinates = heightDiv.getBoundingClientRect();
const iCoordinates = this.getBoundingClientRect();
if (iCoordinates.top > 200) {
imageIndex=0;
drawImage(loadedImages[0]);
return;
} else {
if (imageIndex >= images.length) {
imageIndex = images.length - 1;
}
if (imageIndex < images.length) {
drawImage(loadedImages[imageIndex]);
}
drawImage(loadedImages[imageIndex++])
}
// // const heightDivHeight = parseInt(heightDiv.style.height, 10);
// const top = this.changeFrom + containerHeight;
// const bottom = -(heightDivHeight - containerHeight);
// const range = bottom - top;
// const interval = range / images.length;
// imageIndex = Math.abs(Math.floor((top - coordinates.y) / interval));
};
const drawImage = (img) => {
const canvasWidth = canvas.width = window.innerWidth;
const canvasHeight = canvas.height = window.innerHeight;
const aspectRatio = img.width / img.height;
let newWidth, newHeight;
if (canvasWidth / aspectRatio <= canvasHeight) {
newWidth = canvasWidth;
newHeight = canvasWidth / aspectRatio;
} else {
newHeight = canvasHeight;
newWidth = canvasHeight * aspectRatio;
}
const x = (canvasWidth - newWidth) / 2;
const y = (canvasHeight - newHeight) / 2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, x, y, newWidth, newHeight);
};