1

I'm trying to create a HTML5 canvas using Windows 8 / WinJS. Here's what I have:

    var body = document.getElementById("body");
    var canvas = document.createElement("canvas");
    canvas.id = "myCanvas";

    body.appendChild(canvas);

    var canvasContext = canvas.getContext("2d");

    canvas.width = document.width;
    canvas.height = document.height;

    canvasContext.fillStyle = "#f00";

    canvasContext.fillRect(canvas.width - 100, canvas.height - 50, 100, 50);
    console.log("canvas width " + canvas.width + ",  height " + canvas.height);

Most of this is directly from a tutorial, but for all the tutorials I've seen, the width and height are set to hard coded numbers, for example:

canvas.width = 800;
canvas.height = 600;

Admittedly that does work, but I want the canvas to be as big as the screen, whatever the resolution. How do I achieve this?

4

2 に答える 2

2

これを行うには、ビューポートとビューポートの高さの CSS 値を使用するだけです (これらの情報については、こちらを参照してください) 。

この特定のケースでは、次のことができます。

canvas.style.width = "100vw";
canvas.style.height = "100vh";

このソリューションの利点は、サード パーティのライブラリをロードする必要がないことです。

于 2013-02-25T14:31:43.503 に答える
0

「画面」とは、ブラウザのウィンドウサイズを意味しますか?

その場合は、document.widthとdocument.heightの代わりにwindow.outerWidthとwindow.outerHeightを使用できます。または、jQueryを使用する場合:$(window).width()および$(window).height()。

また、ブラウザのサイズが変更されたときにキャンバスを再初期化できるように、ウィンドウのサイズ変更イベントをリッスンする必要があります。

于 2013-02-25T11:57:14.853 に答える