简体   繁体   English

使画布拉伸以适合图像

[英]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: 但这是正在发生的事情:

在此处输入图片说明

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. 另外,如果图片不是400x300的图片,则会被剪切。 How can I prevent it? 我该如何预防?

通过提供画布的宽度和高度以及ctx.drawImage来尝试:

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

In order to get dynamically your canvas dimensions you could have the following componentWillReceiveProps() method: 为了动态获取画布尺寸,可以使用以下componentWillReceiveProps()方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM