【问题标题】:How to make Three.js FOV responsive to height AND width?如何使 Three.js FOV 响应高度和宽度?
【发布时间】:2019-08-18 16:08:54
【问题描述】:

背景

我使用视口单位调整所有内容:

body {
  font-size: calc((1vw + 1vh) / 2);
}

h6 { 
  font-size: 1em;
}

div { 
  width: 20em;
}

随着屏幕中像素数量的增加,单位的大小也会增加。例如,1920 x 1080 显示器的类型将比 2560 x 1080 显示器小。这允许在无需媒体查询的情况下自动支持超宽、垂直和高 DPI(8k 甚至 16K)显示。

问题

使用 Three.js,对象比例仅响应屏幕的高度。对象在 1920x1080 显示器上的显示尺寸与在 2560x1080 显示器上的尺寸相同。这是因为 Three.js 相机使用垂直视野 (FOV)。

默认行为 - 2560x1080 与 1080x1080 相比。请注意,文本变小了,但 3D 对象的大小保持不变codepen example

我的尝试

Three.js 只响应高度的原因是因为它使用了垂直视角。我尝试使用我在 stackOverflow here 上找到的公式将垂直 fov 更改为对角 fov。

var height = window.innerHeight;
var width = window.innerWidth;
var distance = 1000;
var diag = Math.sqrt((height*height)+(width*width))
var fov = 2 * Math.atan((diag) / (2 * distance)) * (180 / Math.PI);
camera = new THREE.PerspectiveCamera(fov , width / height, 1, distance * 2);
camera.position.set(0, 0, distance);

由此产生的行为与应该发生的相反。

当前结果

Three.js 中的对象只有在增加视口高度时才会变大。我试图将默认的垂直 fov 修改为对角 fov。但是,这不起作用。

想要的结果

调整视口大小时,对象应根据公式 ((视口高度 + 视口宽度) / 2) 改变感知大小。这将确保放置在页面上的文本与 3D 对象保持相同的相对比例。我想通过改变相机而不是 3D 对象本身来实现这一点。

【问题讨论】:

    标签: javascript css three.js responsive-design viewport-units


    【解决方案1】:

    您应该根据屏幕的宽度或高度创建比例。例如:

    SCREEN_WIDTH = window.innerWidth;
    SCREEN_HEIGHT = window.innerHeight;
    
    if(SCREEN_WIDTH > {something} && SCREEN_WIDTH < {something}){
        camera.fov = SCREEN_WIDTH / {something}; //This is your scale ratio.
    };
    
    //Repeat for window.innerHeight or SCREEN_HEIGHT.
    
    if(SCREEN_HEIGHT > {something} && SCREEN_HEIGHT < {something}){
        camera.fov = SCREEN_HEIGHT / {something}; //This is your scale ratio for height, it could be same as window.innerWidth if you wanted.
    };
    
    //Updating SCREEN_WIDTH and SCREEN_HEIGHT as window resizes.
    
    window.addEventListener('resize', onResize, false); //When window is resized, call onResize() function.
    
    function onResize() {
        SCREEN_WIDTH = window.innerWidth; //Re-declaring variables so they are updated based on current sizes.
        SCREEN_HEIGHT = window.innerHeight;
    
        camera.aspect = window.innerWidth / window.innerHeight; //Camera aspect ratio.
        camera.updateProjectionMatrix(); //Updating the display
        renderer.setSize(window.innerWidth, window.innerHeight) //Setting the renderer to the height and width of the window.
    };
    

    希望这会有所帮助!如果您还有任何问题,请告诉我

    -分析

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 2020-11-08
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多