gpt4 book ai didi

javascript - 将图像放入 HTML Canvas(适合宽度和高度)

转载 作者:行者123 更新时间:2023-11-28 05:26:23 25 4
gpt4 key购买 nike

我有这个 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 。而图像具有固定的宽度和高度。

如何拉伸(stretch)该图像以使其完美填充 Canvas ?

最佳答案

drawImage 函数使用dWidthdHeight 参数(MDN) .

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

关于javascript - 将图像放入 HTML Canvas(适合宽度和高度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32014050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com