Threejs canvas size based on container

前端 未结 6 406
借酒劲吻你
借酒劲吻你 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:15

    Maybe I'm missing the point here - but why do the existing suggestions involve resizing the canvas from within the animation loop?

    You'd want your animation loop to do as little as possible, as it will ideally be repeated 30+ times a second, and should be optimized to run as efficiently as possible - affording the maximum fps to the slowest system running it.

    I think there's no harm in calling the resize function from within the resize event listener - much like Meindert Stijfhals suggested below.

    Something like this:

    var container = renderer.domElement.parentElement;
    container.addEventListener('resize', onContainerResize);
    
    function onContainerResize() {
        var box = container.getBoundingClientRect();
        renderer.setSize(box.width, box.height);
    
        camera.aspect = box.width/box.height
        camera.updateProjectionMatrix()
        // optional animate/renderloop call put here for render-on-changes
    }
    

    If you have some kind of render-only-on-changes set up, you can call the render function at the end of the resize function. Otherwise the next time the render loop does fire it should just render with the new settings.

提交回复
热议问题