Put Image Into HTML Canvas (适合宽度和高度)

Put Image Into HTML Canvas (Fit Width and Height)

我有这个 HTML 代码:

<div>
    <canvas id="canvas">
    </canvas>
    <img id="canvasimg" src="{{ $photo }}" style="display:none;"/>
</div>

我有这个 javascript 可以将图像绘制到 HTML Canvas :

<script>
    var canvas = document.getElementById('canvas');
    ctx = canvas.getContext('2d');

    var deviceWidth = window.innerWidth;;

    canvasWidth = deviceWidth - 40;
    canvasHeight = deviceWidth - 40;

    canvas.width = canvasWidth;
    canvas.height = canvasHeight;

    var img = document.getElementById('canvasimg');

    imgx = 0;
    imgy = 0;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, imgx, imgy); 
</script>

问题是当我将此页面加载到宽屏时,它也会产生更宽的 canvas。而图像具有固定的宽度和高度。

如何拉伸该图像以使其完美填充 canvas?

drawImage 函数使用 dWidthdHeight 参数 (MDN)

ctx.drawImage(img, imgx, imgy, canvas.width, canvas.height);