在保持宽高比的 Konva (React Konva) 中制作响应式矩形

Make a responsive rectangle in Konva (React Konva) that maintains aspect ratio

在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。尝试调整浏览器大小 window 以查看它如何保持纵横比。

但我不知道如何使用 Konva 来实现,尤其是 React Konva,我必须使用 widthheightaspectRatio 来保持宽高比.没有padding-top.

我应该怎么做?

注:看起来和How to resize images proportionally / keeping the aspect ratio? but I have tried this solution很像&当我缩小浏览器时它会从原来的位置(width=1024,height=600)跳起来但是当我再次增长它永远不会 returns 到原来的位置 (width=1024, height=600)

这就是我希望我的应用程序的样子:

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

我找到了一个非常酷的解决方案,让我可以做到 →

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

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,
}

编辑: 这没有按预期工作。从原来的宽度跳起来,永远不会 returns 回到原来的宽度。

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

然而,我采用了另一种更简单且效果很好的解决方案:

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

return {
  width,
  height,
}