【问题标题】:How to resize images to fit my canvas?如何调整图像大小以适合我的画布?
【发布时间】:2018-07-11 20:40:44
【问题描述】:

我有不同尺寸的图像,我试图将它们用作画布上的背景。

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>  

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

当我更改为 image 时,它不会调整到我的画布尺寸。

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

【问题讨论】:

  • 您是否关心保持图像的纵横比?
  • "哪个更好,调整我的所有图像或画布的大小?"看你想做什么

标签: javascript html canvas html5-canvas


【解决方案1】:

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

你可以使用:

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

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

如果您的源图像具有不同的纵横比并且将其拉伸到整个画布后面会干扰它,您可以使用以下版本:

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

sx, sy 是源图像的起点 x,起点 y 坐标(在之前的版本中隐含为 0, 0),sWidth, sHeight 是源图像的宽度和高度你想在画布上拾取和放置。

所以使用起始x,起始y和源图像的宽度和高度,您可以巧妙地选择源图像的分区,这样当它在整个画布上拉伸时,纵横比不会失真。

MDN Reference.

【讨论】:

    猜你喜欢
    • 2014-01-27
    • 2014-05-07
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多