Reputation: 33
I am trying to display an image in a Canvas, but for whatever reason the image will not display. I am not getting any errors so I am not sure what the issue is. If anyone could help me out, it would be much appreciated! Here is my code.
import React, { useRef, useEffect } from "react";
const Canvas = (props) => {
const canvasReference = useRef(null);
useEffect(() => {
const canvas = canvasReference.current;
const context = canvas.getContext("2d");
//set properties of the canvas component
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context.fillStyle = "white";
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
const mapImage = new Image();
mapImage.src = "./images/dimensionalDungeonStartingIsland.png";
console.log(mapImage);
mapImage.onload = () => {
context.drawImage(mapImage, 0, 0);
};
//set all the properties again if the window is resized
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context.fillStyle = "white";
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
mapImage.src = "./images/photo.jpg";
mapImage.onload = () => {
context.drawImage(mapImage, 0, 0);
};
});
}, []);
return <canvas ref={canvasReference} />;
};
export default Canvas;
Upvotes: 2
Views: 41
Reputation: 17594
Your code looks good, only thing I could think of is that source:
mapImage.src = "./images/dimensionalDungeonStartingIsland.png";
...
mapImage.src = "./images/photo.jpg"
are you sure that image exists on that location?
I tried with a different image and it loaded fine:
const mapImage = new Image();
mapImage.src = "https://i.sstatic.net/UFBxY.png";
mapImage.onload = () => {
context.drawImage(mapImage, 0, 0);
};
here is a fiddle:
https://jsfiddle.net/heldersepu/mayspw5v/15/
Upvotes: 1