0

I have a canvas in which I want to render various images, depending on the user. Right now the canvas is fixed size like this:

<canvas width="400" height="300" id={'canvas'}/>

This is how I'm rendering the image:

componentWillReceiveProps(nextProps) {
    const ctx = document.getElementById('canvas').getContext('2d');
    const img = new Image();

    img.onload = function () {
        ctx.drawImage(img, 0, 0);
    };
    img.src = URL.createObjectURL(nextProps.image)
}

But this is what's happening:

enter image description here

So the image at the bottom is too big to be in the canvas, and the other image is too small to fill the image. Also if the image is anything other then a 400x300, it gets cut. How can I prevent it?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Alex Ironside
  • 4,658
  • 11
  • 59
  • 119
  • This might help you, Please have a look at it https://stackoverflow.com/questions/21961839/simulation-background-size-cover-in-canvas/21961894#21961894 – chintuyadavsara Dec 11 '18 at 11:54

2 Answers2

1

try by providing the canvas width and height along with ctx.drawImage like:

ctx.drawImage(img, 0, 0, 400, 300);
Sarath Raj
  • 139
  • 1
  • 7
1

In order to get dynamically your canvas dimensions you could have the following componentWillReceiveProps() method:

componentWillReceiveProps(nextProps) {
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();

    img.onload = function () {
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    };
    img.src = URL.createObjectURL(nextProps.image)
}
dmraptis
  • 909
  • 1
  • 10
  • 22