根据 JavaScript 中的宽度使高度响应

Make height responsive according to width in JavaScript

我有一个矩形,我想根据宽度进行响应。

目前,我的逻辑是直截了当的:

aspectRatio = 16 / 9
win = {
    width: window.innerWidth,
    height: window.innerHeight,
}

get browser() {
    const width = this.win.width - 250
    const height = width / this.aspectRatio

    return {
        width,
        height,
    }
}

我通过从 win.width 中减去边栏宽度 250 来计算我的 width

对于我的 height,我将 width 除以 aspectRatio

但是,当我将 window 大小减小到 ~700px 时,这会导致高度为 0。

我的申请看起来像:

演示 → https://gqhhl.csb.app/

代码沙盒 → https://codesandbox.io/s/add-padding-to-centered-canvas-with-sidebar-gqhhl

我真正想要的是那个木瓜鞭矩形响应。我不确定要使用哪种算法?我正在使用 Canvas 使用 KonvaJS 但逻辑在 JavaScript.

如何使它具有响应性和比例性?目前,身高变短的速度非常快。

第一个解决方案

width: 100%;
padding-top: 56.25%; /* 16:9 Aspect Ratio */

第二种解决方案

padding-top: calc(9 / 16 * 100%);

您需要更改 CSS 但假设您的组件被埋在 3 层深处。与 CSS 文件不同,它位于您的 .tsx 旁边并且已经导入,所以请使用它!

您的代码第 5 行:

import "./styles.css"

将其添加到文件末尾(从@deadcoder 解决比例问题的答案中复制)。另请参阅其下方的断点,了解响应式断点的运行方式。这就是你如何在不缩水的情况下做出响应的事情。

canvas {
  width: 100%;
  padding-top: 56.25%; /* 16:9 Aspect Ratio */
}

@media screen and (max-width: 1200px) {
    canvas {
      width: 100%;
      height: 400px;
      padding: 0; /* reset the ratio for smaller sizes so you can crop it */
    }
}
@media screen and (max-width: 600px) {
    canvas {
      width: 100%;
      height: 200px;
      padding: 0; /* reset the ratio for smaller sizes so you can crop it */
    }
}

也可以考虑给 canvas 一个 ID 或 class 来挑出它。

如果高度仍然消失得太快,请考虑使用整个区域作为 canvas 或使用背景图像

这是我的解决方案:

function App() {
  const store = useStore();
  const { win, browser, aspectRatio } = store;
  const pad = 50;

  const rectWidth = browser.width - pad;
  const rectHeight = rectWidth / aspectRatio;

  return (
    <div className="flex">
      <div id="sidebar">
        <h1 className="text">
          Center <span>papayawhip</span> Canvas
        </h1>
      </div>
      <Stage width={browser.width} height={browser.height} id="konva">
        <Layer>
          <Rect
            width={rectWidth}
            height={rectHeight}
            x={pad / 2}
            y={(win.height - rectHeight) / 2}
            fill="papayawhip"
          />
        </Layer>
      </Stage>
    </div>
  );
}

另外,我换了店铺,所以browserreturnscanvas地区:

get browser() {
        const width = this.win.width - 250
        const height = this.win.height

        return {
            width,
            height,
        }
}

演示:https://codesandbox.io/s/react-konva-responsive-canvas-ogk1n