根据JavaScript中的宽度使高度响应
我有一个矩形,我想根据宽度做出响应 目前,我的逻辑是直截了当的:根据JavaScript中的宽度使高度响应,javascript,html,css,canvas,konvajs,Javascript,Html,Css,Canvas,Konvajs,我有一个矩形,我想根据宽度做出响应 目前,我的逻辑是直截了当的: aspectRatio = 16 / 9 win = { width: window.innerWidth, height: window.innerHeight, } get browser() { const width = this.win.width - 250 const height = width / this.aspectRatio return { wi
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
对于我的高度
,我将宽度
除以aspectRatio
但是,当我将窗口大小减小到~700px时,这将导致高度为0
我的应用程序看起来像:
演示→
代码沙盒→
我真正想要的是那个木瓜鞭长方形的反应灵敏。我不确定使用哪种算法?我使用的画布是KonvaJS,但逻辑是JavaScript
如何使其响应性和比例性?目前,高度缩短得非常快。第一种解决方案
width: 100%;
padding-top: 56.25%; /* 16:9 Aspect Ratio */
第二种解决方案
padding-top: calc(9 / 16 * 100%);
您需要更改CSS,但要说您的组件被深埋了3层。与CSS文件不同,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 */
}
}
也考虑将画布赋予ID或类来单列出来。
如果高度消失得太快,考虑使用整个区域作为画布或使用背景图像
< P>这里是我的解决方案:函数应用程序(){
const store=useStore();
const{win,browser,aspectRatio}=store;
常数pad=50;
const rectWidth=browser.width-pad;
const rectHeight=rectWidth/aspectRatio;
返回(
中心木瓜鞭帆布
);
}
此外,我还更改了存储,因此浏览器
返回画布区域:
get browser(){
const width=this.win.width-250
常量高度=this.win.height
返回{
宽度,
高度,
}
}
演示:我正在使用Konva,但我不能使用填充,尽管我很喜欢使用第一种解决方案,因为这是实现我想要的最好方法。我不能使用它的原因是因为我的组件深入到了2-3个级别(使用React),这就是我想要JS解决方案的原因