React beginner here, I'm getting this error 'Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.' i have been stuck with this for few hours now.
That error is showing on drawImage which is inside if statement. Is there a way to tell it if there is an image then go on and draw it ( ctx.drawImage(img, 0, 0)), but if there isnt any image then dont give any error(dont show any image either), something like what Optional chaining (?.) does ?
English is not my mother language so could be mistakes.
my code:
const CameraCanvas = useRef<any>();
const CameraImage = useRef<any>();
const updatePreviewUrl = () => {
if (currentCam) {
let curSnapshotUrl = state.snapshot?.snapshotUrl.split("?ts=")[0];
let newSnapshotUrl =
`api/cam/${....}/` +
`${curCam.ident}/snapsht`;
if (curSnapshotUrl ....) {
setState({
...
});
}
}
};
const updateCanvas = () => {
updatePreviewUrl();
const canvas = CameraCanvas.current;
const ctx = canvas.getContext("2d");
const img = CameraImage.current;
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fill();
if (currentCam) {
ctx.drawImage(img, 0, 0);
}
};
useEffect(() => {
updateCanvas();
const img = CameraImage.current;
img.onload = updateCanvas;
return () => {
img.onload = null;
};
});