Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda