【问题标题】:Make a responsive rectangle in Konva (React Konva) that maintains aspect ratio在 Konva (React Konva) 中制作一个保持纵横比的响应式矩形
【发布时间】:2021-04-03 09:59:30
【问题描述】:

在 CSS 中,我可以这样做:

<div class="aspect-ratio-box"></div>
body {
  max-width: 1366px;
  margin: 0 auto;
  padding: 20px;
}

.aspect-ratio-box {
  height: 0;
  padding-top: 56.25%;
  background: red;
}

这是CodePen。尝试调整浏览器窗口的大小,看看它如何保持纵横比。

但我不知道如何使用 Konva,尤其是 React Konva,我必须使用 widthheightaspectRatio 来保持纵横比。没有padding-top

我该怎么做?

注意:它看起来类似于How to resize images proportionally / keeping the aspect ratio?,但我尝试过this solution,当我缩小浏览器时它会从原始位置(宽度=1024,高度=600)跳起来但是当我再次增长它永远不会回到原来的位置(宽度=1024,高度=600)

这就是我希望我的应用看起来的样子:

基本上我想在JS中完成中心的白色部分,因为我需要使用Canvas。

【问题讨论】:

标签: html css aspect-ratio konvajs react-konva


【解决方案1】:

我找到了一个非常酷的解决方案,让我可以这样做 → https://stackoverflow.com/a/14731922/6141587

我根据自己的需要对其进行了调整:

const maxWidth = window.innerWidth * 0.9
const maxHeight = window.innerHeight * 0.9
const width = 1366
const height = 768
const ratio = Math.min(maxWidth / width, maxHeight / height)

return {
  width: width * ratio,
  height: height * ratio,
}

编辑:这没有按预期工作。从原始宽度向上跳跃并且永远不会返回到原始宽度。

编辑 2: 我认为这是按预期工作的。我正在将我的width 重置为width * 0.8,所以它永远不会回到原来的宽度,否则它可能工作正常。

但是我选择了另一个更简单的解决方案,效果很好:

const aspectRatio = 16 / 9
const width = window.innerWidth * 0.8
const height = width / aspectRatio

return {
  width,
  height,
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 2020-08-23
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2017-10-26
    相关资源
    最近更新 更多