且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HTML5 Canvas 100%Viewport的宽度高度?

更新时间:2023-12-06 17:32:58

示例: http://jsfiddle.net/jaredwilli/qFuDr/

<canvas id="canvas"></canvas>



JavaScript



JavaScript

(function() {
    var canvas = document.getElementById('canvas'),
            context = canvas.getContext('2d');

    // resize the canvas to fill browser window dynamically
    window.addEventListener('resize', resizeCanvas, false);

    function resizeCanvas() {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            /**
             * Your drawings need to be inside this function otherwise they will be reset when 
             * you resize the browser window and the canvas goes will be cleared.
             */
            drawStuff(); 
    }
    resizeCanvas();

    function drawStuff() {
            // do your drawing stuff here
    }
})();



CSS



CSS

* { margin:0; padding:0; } /* to remove the top and left whitespace */

html, body { width:100%; height:100%; } /* just to be sure these are full screen*/

canvas { display:block; } /* To remove the scrollbars */

这是如何正确地使画布全宽和高度的浏览器。你只需要把所有的绘图代码放到drawStuff()函数的canvas中。

That is how you properly make the canvas full width and height of the browser. You just have to put all the code for drawing to the canvas in the drawStuff() function.