HTML5 Canvas 100%Viewport的宽度高度? [英] HTML5 Canvas 100% Width Height of Viewport?

查看:526
本文介绍了HTML5 Canvas 100%Viewport的宽度高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个占用100%的视口宽度和高度的canvas元素。

I am trying to create a canvas element that takes up 100% of the width and height of the viewport.

您可以在我的示例中看到这里发生,但它是在Chrome和FireFox中添加滚动条。

You can see in my example here that is occurring, however it is adding scroll bars in both Chrome and FireFox. How can I prevent the extra scroll bars and just provide exactly the width and height of the window to be the size of the canvas?

推荐答案

示例: 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.

这篇关于HTML5 Canvas 100%Viewport的宽度高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆