I have 640×692 jpg (Emperor_Penguin_Manchot_empereur.jpg). and I want to paste this in canvas.
So, I made the canvas
const canvasRef = useRef();
useEffect(() =>{
var chara= new Image();
chara.src = "http://localhost:8021/Emperor_Penguin_Manchot_empereur.jpg";
chara.onload = () => {
var ctx = canvasRef.current.getContext('2d');
ctx.drawImage(chara,0,0,640,692,0,0,640,692);// paste the image as the same size.
}
return
<canvas ref={canvasRef} style={{width:640,height:692}}></canvas>
this is the picture,
result
However with this script, it shows the only the part of this picture (left top).
I set the size of canvas and jpg as the same size.
Where am I wrong??
2
Answers
You need to explicitly define your canvas’s dimensions/resolution, e.g.:
Without it, the browser uses some default like, 300px × 150px. All your CSS does is stretch the canvas to be 640px × 692px, it doesn’t actually make the canvas resolution larger.
The code has a few errors. First, does not set the canvas’s width and height to the image’s width and height. This resulted in the image being scaled to fit the canvas. Second, it does not create a new 2D context for the canvas. This resulted in the image being drawn to the canvas using the default 2D context, which is not always what you want.