入門

2012-11-23 124 views
0

我創建了一個簡單的canvas元素入門

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

當我試圖讓高度,但是在javascript canvas元素的高度:

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 

如何在地球上得到0在js中測量?

+1

見接受這個問題的答案http://stackoverflow.com/questions/4938346/canvas-width-and-height-in-html5 – Musa

回答

1

由於@Alex說,可以使用getComputedStyle函數來獲取當前大小的畫布

但是...使畫布全屏幕寬度和高度始終,這意味着即使在瀏覽器的大小時,就需要重新調整該畫布到window.innerHeightwindow.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; } 
0

我們可以窺探計算出來的樣式!

document.defaultView.getComputedStyle(canvas).height 
document.defaultView.getComputedStyle(canvas).width 
+0

的getComputedStyle'(畫布)的最後一位.height '夠了。 – mab