Search code examples
javascriptreactjscanvas

Paste a image to the canvas for full size


I have 640x692 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,

enter image description here

result

enter image description here

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??


Solution

  • 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.

    const canvasRef = useRef();
    
    useEffect(() => {
      const chara = new Image();
    chara.src ="http://localhost:8021/Emperor_Penguin_Manchot_empereur.jpg";
    
    chara.onload = () => {
      const ctx = canvasRef.current.getContext('2d');
      ctx.drawImage(chara, 0, 0);
    };
    }, []);
    
    return (
      <canvas ref={canvasRef} style={{width: 640, height: 692}} />
    );