gpt4 book ai didi

javascript - 如何调整图像大小以适合我的 Canvas ?

转载 作者:行者123 更新时间:2023-12-03 02:35:10 26 4
gpt4 key购买 nike

我有不同尺寸的图像,我正在尝试将它们用作 Canvas 上的背景。

index.html:

<!DOCTYPE html>
<html>
<head>
<title>js</title>
</head>
<body onLoad='init2()'>
<canvas id="canvas" width="1000" height="1000">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

<!-- This image will be displayed on the canvas -->
<img id="myImage" src="https://image.slidesharecdn.com/bareconf-140329111624-phpapp02/95/draft-scientific-paper-1-638.jpg?cb=1396091812" style = "display: none">
</body>
</html>

如何将所有图像调整为固定的 Canvas 尺寸?这是完整的code

当我更改为这个image时,它没有调整到我的 Canvas 尺寸。

调整所有图像或 Canvas 的大小哪个更好?

最佳答案

您可以使用drawImage4rth5th参数来定义源图像的目标宽度和高度。

您可以使用:

void ctx.drawImage(image, dx, dy, dWidth, dHeight);

如果您将 dx, dy 提供为 0, 0(正如您在示例代码中已提供的那样)以及 dWidthdHeight Canvas 宽度和高度,源图像将拉伸(stretch)到整个 Canvas 。

如果您的源图像具有不同的宽高比,并且将其拉伸(stretch)到整个 Canvas 后面会干扰它,您可以使用以下版本:

void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

sx, sy 是源图像的起始 x、起始 y 坐标(在以前的版本中隐式为 0, 0)和 sWidth, sHeight 是您要拾取并放置在 Canvas 上的源图像的宽度和高度。

因此,使用起始 x、起始 y 以及源图像的宽度和高度,您可以巧妙地选择源图像的分区,以便当它在整个 Canvas 上拉伸(stretch)时,宽高比不会扭曲。

MDN Reference .

关于javascript - 如何调整图像大小以适合我的 Canvas ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48564164/

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