Resize HTML5 canvas to fit window

前端 未结 16 1150
遥遥无期
遥遥无期 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:27

    (function() {
    
        // get viewport size
        getViewportSize = function() {
            return {
                height: window.innerHeight,
                width:  window.innerWidth
            };
        };
    
        // update canvas size
        updateSizes = function() {
            var viewportSize = getViewportSize();
            $('#myCanvas').width(viewportSize.width).height(viewportSize.height);
            $('#myCanvas').attr('width', viewportSize.width).attr('height', viewportSize.height);
        };
    
        // run on load
        updateSizes();
    
        // handle window resizing
        $(window).on('resize', function() {
            updateSizes();
        });
    
    }());
    

提交回复
热议问题