无法让 Canvas 显示图像

Having trouble getting a Canvas to display an image

我正尝试在 Canvas 中显示图像,但由于某种原因图像无法显示。我没有收到任何错误,所以我不确定是什么问题。如果有人可以帮助我,将不胜感激!这是我的代码。

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;

你的代码看起来不错,我唯一能想到的就是来源:

mapImage.src = "./images/dimensionalDungeonStartingIsland.png";
...
mapImage.src = "./images/photo.jpg"

您确定该位置存在图像吗?

我尝试使用不同的图像并且它加载正常:

    const mapImage = new Image();
    mapImage.src = "http://i.stack.imgur.com/UFBxY.png";
    mapImage.onload = () => {
      context.drawImage(mapImage, 0, 0);
    };

这是一个 fiddle:
https://jsfiddle.net/heldersepu/mayspw5v/15/