【问题标题】:Scale down <canvas> within grid container so, that <canvas> retains its aspect ratio在网格容器中缩小 <canvas> 以便 <canvas> 保持其纵横比
【发布时间】:2019-10-24 03:05:33
【问题描述】:

我在缩小属于grid 容器的canvas 元素时遇到问题。

html * {
 font-size: 1em;
 font-family: Arial;
}

#wrapper {
 border: 1px solid green;
 display: grid;
 grid-template-columns: repeat(auto-fit, 32vmin);
 grid-auto-rows: minmax(32vmin, 43vmin);
 grid-column-gap: 0.4em;
 grid-row-gap: 0.4em;
 align-items: center;
 justify-items: center;
}

#wrapper > * {
 object-fit: contain;
 max-height: 32vmin;
 max-width: 32vmin;
 border: 1px solid black;
}

#canvas0 {
 width:20vmin;
 height:60vmin;
}
<html>
<body>
 <div id="wrapper">
  <canvas id="canvas0"></canvas>
 </div>
</body>
</html>

上面的代码显示canvas 具有width: 20height: 60,结果纵横比为1:2。我需要的是一个canvas 元素,它适合最大grid 行高和列宽,并且在纵横比方面保持不变。

【问题讨论】:

    标签: javascript html css css-grid object-fit


    【解决方案1】:

    我想出了一个使用Javascript 的解决方案。正如我现在所看到的,canvas 元素必须有自己的widthheight 属性,这些属性不同于CSS 属性。画布widthheight 是用于在画布上绘图的尺寸。 CSS widthheight 代表元素布局。

    CSS 加上HTML 布局与原始问题基本相同。这里和那里几乎没有变化,但大体相同。之后,我将widthheight 设置为Javascript 中的每个canvas 元素,从服务器获取尺寸和纵横比。然后我根据纵横比缩放canvas 元素。

    这个 SO 答案和问题帮助我解决了扩展问题。

    How do I scale one rectangle to the maximum size possible within another rectangle?

    【讨论】:

      最近更新 更多