Search code examples
htmlreactjshtml5-canvas

HTML canvas not drawing image


I have a react app but when I try to load an image is not drawing it on the canvas. Here is the code:

 import React , {useRef, useEffect, useState} from "react";
import image from '../assets/tesis/1_cuarto.JPG';
import imageBed from '../assets/tesis/1_cama.PNG';

export default function Canvas(props) {
  
  
  
  const canvasRef = useRef(null);

  //const [bed, setBed] = useState(new Image());

  useEffect(() => {


    const canvas = canvasRef.current
    const context = canvas.getContext('2d');
    let bed = new Image();
    bed.src = imageBed;
    //Our first draw
    //context.fillRect(0, 0, context.canvas.width, context.canvas.height)
    bed.onload = () => {
      console.log(bed)
      context.drawImage(bed, 0, 0);
    };


  }, []);

  return (
      <canvas id="canvas" /*style={{height: '100%', width:'100%', position: 'absolute', backgroundImage: `url(${image})` , backgroundPosition: 'center', backgroundRepeat: 'no-repeat', backgroundSize:'cover'}}*/ ref={canvasRef} />
  );
}

When I check the console the path points me to the image and it load, but the canvas is not drawing it.

Here is the console

enter image description here

enter image description here


Solution

  • There is a lot of transparency in the upper left corner of your image.

    • According to the w3 spec, the canvas defaults to 300 x 150, so it is probably getting cropped/clipped.

    • Also, you cannot use style/CSS to change the dimensions of your <canvas> as this only stretches the image without increasing the number of drawable pixels. You have to explicitly set the width and height properties.

      Do this either directly with attributes in HTML:

      <canvas width="600" height="600">
      

      Or in JS:

      canvas.width = 600;
      canvas.height = 600;
      

      For a more dynamic, window-size dependent solution in JS, see this answer.