简体   繁体   English

Three.js –如何在不调整渲染器大小或缩放内容的情况下调整画布大小?

[英]Three.js – how to resize canvas without resizing renderer or scaling contents?

I'm making a website with a Three.js canvas that fills the viewport. 我正在使用Three.js画布填充视口的网站。 I'd like it to remain visually unchanged when resizing the window, ie. 我希望它在调整窗口大小时保持外观不变。 no scaling at all. 完全没有缩放比例。

Currently here's what I'm doing: 目前,这是我正在做的事情:

  • renderer.setSize(window.screen.width, window.screen.height)
  • Then, on init and resize: 然后,在init上调整大小:
    • camera.fov = window.innerHeight / window.screen.height;
    • camera.aspect = window.innerWidth / window.innerHeight;
    • renderer.setViewport(0, 0, window.innerWidth, window.innerHeight);


This works, but I'm concerned that maybe it's inefficient, since the renderer size is the same whether the browser is in full screen or just a tiny window. 这行得通,但是我担心它效率不高,因为无论浏览器是全屏还是小窗口,渲染器的大小都是相同的。 Does setViewport successfully limit the calculations needed for each frame or is everything basically still calculated and then cropped? setViewport是否成功限制了每一帧所需的计算,还是基本上所有内容仍在计算之后又被裁剪了?

One answer to this can be found in the official documentation, I couldn't see it at first because it's hidden in the FAQs : 对此的一个答案可以在官方文档中找到,起初我看不到它,因为它隐藏在FAQ中

visible_height = 2 * Math.tan( ( Math.PI / 180 ) * camera.fov / 2 ) * distance_from_camera;

Here's an adapted version (do this on resize – or rather, save the window dimensions and use the saved values in a throttled function): 这是一个适应的版本(在调整大小时执行此操作–或更确切地说,保存窗口尺寸并在节流函数中使用保存的值):

renderer.setSize(window.innerWidth, window.innerHeight);
camera.fov = Math.atan(window.innerHeight / 2 / camera.position.z) * 2 * THREE.Math.RAD2DEG;
camera.aspect = window.innerWidth / window.innerHeight;

Also important not to forget camera.updateProjectionMatrix(); 同样重要的是不要忘记camera.updateProjectionMatrix(); !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM