Threejs canvas size based on container

前端 未结 6 424
借酒劲吻你
借酒劲吻你 2021-02-01 20:58

How can I calculate canvas size based on its container? To avoid scrolling.

If I set the size based on window the canvas is too big.

6条回答
  •  孤街浪徒
    2021-02-01 21:08

    Here's the code that allowed me to get a handle on my canvas rendering size:

    First, the scene is rendered inside a

    which has the dimensions of your choice:

    CSS:

    .relative {
        position: relative;
    }
    
    h-512 {
        height: 51.2rem;
    }
    
    w-512 {
        width: 51.2rem;
    }
    
    #your_scene {
        overflow: hidden;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }
    

    Then, you grab the dimensions of it:

    this.mount = document.querySelector('#your_scene');
    this.width = document.querySelector('#your_scene').offsetWidth;
    this.height = document.querySelector('#your_scene').offsetHeight;
    

    Then, you (in my case) set the renderer background to transparent, set pixel ratio, and then apply the size of the container to the renderer. Three.js works by appending the your_scene container with the renderer element, so that's why the final step here is to appendChild:

    this.renderer = new THREE.WebGLRenderer({ alpha: true });
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(this.width, this.height);
    this.mount.appendChild(this.renderer.domElement);
    

    That should hopefully be enough to allow someone to get forensic on their scene. The part doing the most work is the setSize call, but you need to have the correct dimensions, and additionally, your camera must be pointed in the correct spot.

    If you have your code similar to mine, but it still doesn't work, look at your camera perspective and make sure your scene objects are actually in view.

提交回复
热议问题