I have a list of 150 images called 0001.jpg, 0002.jpg … 0150.jpg.
This is what I’m doing so far (only included the relevant code):
import React, { useRef, useEffect, useState } from 'react';
function getCurrentFrame(index) {
return `../${index.toString().padStart(4, "0")}.jpg`;
}
const ImageCanvas = ({ scrollHeight, numFrames, width, height }) => {
const canvasRef = useRef(null);
const [images, setImages] = useState([]);
const [frameIndex, setFrameIndex] = useState(0);
// Step 1: Load images
function preloadImages() {
for (let i = 1; i <= numFrames; i++) {
const img = new Image();
const imgSrc = getCurrentFrame(i);
img.src = imgSrc;
setImages((prevImages) => [...prevImages, img]);
}
}
const render = () => {
console.log(images[frameIndex]);
context.drawImage(images[frameIndex], 0, 0);
requestId = requestAnimationFrame(render);
};
render();
I get this error when it tries to drawImage:
“Uncaught DOMException: Failed to execute ‘drawImage’ on ‘CanvasRenderingContext2D’: The HTMLImageElement provided is in the ‘broken’ state.
at render”
console.log(images[frameIndex]); prints the correct element three to five times before showing the error:
<img src="../0001.jpg">
I’m certain the image source is correct because I set “img.src” in preloadImages() to the same src “../0001.jpg” and it shows the image.
Any idea what could be going wrong? Is there a better way to do it?