我有这个 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
函数使用dWidth
和dHeight
参数(MDN) .
ctx.drawImage(img, imgx, imgy, canvas.width, canvas.height);
关于javascript - 将图像放入 HTML Canvas(适合宽度和高度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32014050/