在JavaScript中保持矩形的纵横比

8 浏览
0 Comments

在JavaScript中保持矩形的纵横比

我有以下Codepen代码:\n

  window.addEventListener('resize', function updateBox() {
  const maxWidth = window.innerWidth * 0.8
  const maxHeight = window.innerHeight * 0.8
  const width = 1024
  const height = 600
  const ratio = Math.min(maxWidth / width, maxHeight / height)
  const box = document.getElementById("box")
  console.log(`resize: ${width*ratio}*${height*ratio}`)
  box.style = `width: ${width * ratio}px;`
  box.style = `height: ${height * ratio}px;`
});

\n

#box {
  width: 1024px;
  height: 600px;
  background-color: red;
}

\n


\n这段代码是从一个流行的问题How to resize images proportionally / keeping the aspect ratio?中摘录出来的。这是一个非常受欢迎的答案,但它无法保持完美的宽高比。\n从浏览器窗口的调整中可以看到,它的效果很奇怪。它无法保持宽高比,而是在宽度和高度上进行了一些随机计算,导致矩形跳动。\n我想要的效果类似于https://codepen.io/chriscoyier/pen/BZNoev。尝试调整浏览器大小以查看效果。矩形保持其宽高比并保持在中心位置。\n不幸的是,我不能使用它,因为它使用了CSS的padding-top,所以我不能使用它。我需要使用JS来实现这个效果,因为我将使用名为Konva的Canvas库。\n我该如何做到这一点?

0