如何使Three.js FOV响应高度和宽度?

7

背景

我使用视口单位来调整所有大小:

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)。
默认行为 - 与 1080x1080 相比的 2560x1080。请注意,“文本变小了,但 3D 对象的大小保持不变”。代码示例请参见此codepen
我的尝试:Three.js 之所以仅响应高度是因为它使用垂直视野(fov)。我尝试使用我在 stackOverflow 中找到的这个公式更改垂直 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对象本身来实现这一点。

1个回答

0
你应该根据屏幕的宽度或高度创建一个比例尺。例如:
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.
};

希望这能帮到你!如果你还有任何问题,请告诉我。

- Anayttal


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接