入门

2012-11-23 84 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