微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Konva (React Konva) 中制作一个保持纵横比的响应矩形

如何解决在 Konva (React Konva) 中制作一个保持纵横比的响应矩形

在 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)

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

browser-window

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

解决方法

我找到了一个非常酷的解决方案,可以让我做到这一点 → 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,}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。