Resize HTML5 canvas to fit window

前端 未结 16 1614
遥遥无期
遥遥无期 2020-11-22 12:03

How can I automatically scale the HTML5 element to fit the page?

For example, I can get a

to scale by setting th
16条回答
  •  广开言路
    2020-11-22 12:33

    function resize() {
    
        var canvas = document.getElementById('game');
        var canvasRatio = canvas.height / canvas.width;
        var windowRatio = window.innerHeight / window.innerWidth;
        var width;
        var height;
    
        if (windowRatio < canvasRatio) {
            height = window.innerHeight;
            width = height / canvasRatio;
        } else {
            width = window.innerWidth;
            height = width * canvasRatio;
        }
    
        canvas.style.width = width + 'px';
        canvas.style.height = height + 'px';
    };
    
    window.addEventListener('resize', resize, false);
    

提交回复
热议问题