简体   繁体   中英

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. 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:
    • 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?

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 :

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(); !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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