Alex Ironside
Alex Ironside

Reputation: 5039

Make canvas stretch to fit image

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?

Upvotes: 0

Views: 74

Answers (2)

dmraptis
dmraptis

Reputation: 929

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)
}

Upvotes: 1

Sarath Raj
Sarath Raj

Reputation: 139

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

ctx.drawImage(img, 0, 0, 400, 300);

Upvotes: 1

Related Questions