I have utilized the premium version and incorporated a frame-by-frame PNG animation in the next js project. However, I consistently encounter issues; the page functions correctly only after refreshing it. I have added my code below.
'use client';
import React, { useEffect, useRef } from "react";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);
const LineAnimation1 = () => {
const canvasRef = useRef(null);
useEffect(() => {
const initCanvas = () => {
const canvas = canvasRef.current;
const context = canvas.getContext("2d");
canvas.width = window.innerHeight * 0.1;
canvas.height = window.innerHeight * 0.2;
window.addEventListener("resize", function () {
canvas.width = window.innerHeight * 0.1;
canvas.height = window.innerHeight * 0.2;
render();
});
const frameCount = 14;
const currentFrame = (index) => {
const imagePath = `https://candokidsbastg.wpengine.com/test/lineanimation/1/Line_${(index + 1)
.toString()
.padStart(2, "0")}.png`;
console.log(imagePath);
return imagePath;
};
const images = [];
const sequence = {
frame: 0,
};
let loadedImages = 0;
for (let i = 0; i < frameCount; i++) {
const img = new Image();
img.src = currentFrame(i);
img.onload = () => {
loadedImages++;
if (loadedImages === frameCount) {
// All images have loaded, trigger render
render();
}
};
images.push(img);
}
gsap.to(sequence, {
frame: frameCount + 1,
snap: "frame",
ease: "power1.inOut",
duration: 4,
scrollTrigger: {
scrub: 3,
start: "top 60%",
end: "top 100%",
trigger: ".case-banner",
markers: true
},
onUpdate: render,
});
function render() {
if (loadedImages === frameCount) {
const frameIndex = Math.max(0, Math.min(sequence.frame, frameCount - 1));
scaleImage(images[frameIndex], context);
}
}
function scaleImage(img, ctx) {
var canvas = ctx.canvas;
var hRatio = canvas.width / img.width;
var vRatio = canvas.height / img.height;
var ratio = Math.max(hRatio, vRatio);
var centerShift_x = (canvas.width - img.width * ratio) / 2;
var centerShift_y = (canvas.height - img.height * ratio) / 2;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(
img,
0,
0,
img.width,
img.height,
centerShift_x,
centerShift_y,
img.width * ratio,
img.height * ratio
);
}
};
initCanvas();
}, []);
return <canvas id="page01" className="" ref={canvasRef}></canvas>;
};
export default LineAnimation1;