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
CodePudding user response:
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 thewidth
andheight
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: https://stackoverflow.com/a/7794470/4294399
CodePudding user response:
It seems to work fine in plain HTML, so probably something wrong with the ref or the image directory.
const canvas = document.getElementById("ImgCanvas");
const ctx = canvas.getContext('2d');
let bed = new Image();
bed.src = 'https://images.unsplash.com/photo-1615874959474-d609969a20ed?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=580&q=80';
bed.onload = () => {
ctx.drawImage(bed, 0, 0);
};
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<canvas id="ImgCanvas" style="border: 1px solid black;" width="1000px" height="600px"></canvas>
</body>
</html>