Threejs canvas size based on container

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

    I think that the best way to resize the canvas is not the accepted answer above. Every animationframe @gman will run the function resizeCanvasToDisplaySize, doing multiple calculations.

    I think that the best way is to create a window event lister 'resize' and a boolean saying wether the user resized or not. In the animation frame you can check wether the user resized. If he resized, you can resize the canvas in the animationframe.

    let resized = false
    
    // resize event listener
    window.addEventListener('resize', function() {
        resized = true
    })
    
    function animate(time) {
        time *= 0.001
    
        if (resized) resize()
    
        // rotate the cube
        cube.rotation.x += 0.01
        cube.rotation.y += 0.01
    
        // render the view
        renderer.render(scene, camera)
    
        // animate
        requestAnimationFrame(animate)
    }
    
    function resize() {
        resized = false
    
        // update the size
        renderer.setSize(window.innerWidth, window.innerHeight)
    
        // update the camera
        const canvas = renderer.domElement
        camera.aspect = canvas.clientWidth/canvas.clientHeight
        camera.updateProjectionMatrix()
    }
    

提交回复
热议问题