0

シンプルなキャンバス要素を作成しました

<canvas style="width:100%;height:100%;" id="canvas"></canvas>

ただし、高さを取得しようとすると、javascriptでは次のようになります。

var canvas = document.getElementById(config.elementId);
console.log(canvas.height); //150
console.log(canvas.width); //300

console.log(canvas.style.height); //100%
console.log(canvas.style.width); //100%

chromeのデバッガーで要素を調べ、実際に要素の上にマウスを置くと、chromeは要素のサイズを次のように報告します。

1627x925px

いったいどうやって1627x925pxjsの測定値にたどり着くのですか?

4

2 に答える 2

1

@Alex が言うように、関数を使用しgetComputedStyleてキャンバスの現在のサイズを取得できます。

しかし...window.innerHeightキャンバスを常にフルスクリーンの幅と高さにするには、ブラウザのサイズが変更された場合でも、キャンバスのサイズをおよびに変更する関数内で描画ループを実行する必要がありますwindow.innerWidth

それができたら、通常の関数canvas.heightcanvas.width関数を使用して、キャンバスのサイズを適切に取得できます。

(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
         * to avoid canvas to be cleared. */
        drawStuff(); 
    }
    resizeCanvas();

    function drawStuff() {
        console.log(canvas.height); //925
        console.log(canvas.width); //1627
        // do your drawing stuff here
    }
})();

プラス:この CSS ハックを使用して、問題なくキャンバスをフル サイズにします。

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

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

/* To remove the scrollbar */
canvas { display:block; } 
于 2012-11-23T07:30:19.730 に答える
0

計算されたスタイルをスパイすることができます!

document.defaultView.getComputedStyle(canvas).height
document.defaultView.getComputedStyle(canvas).width
于 2012-11-23T06:45:55.500 に答える