Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Having trouble getting a Canvas to display an image

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;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 = "http://i.stack.imgur.com/UFBxY.png";
    mapImage.onload = () => {
      context.drawImage(mapImage, 0, 0);
    };

here is a fiddle:
https://jsfiddle.net/heldersepu/mayspw5v/15/

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!