2014-11-23 142 views

回答

2

是,这些单位总是像素并应用到 canvas元素使用。但是,如果在使用CSS的元素上没有定义大小(即style属性或使用样式表),则该元素将自动采用其位图的大小。

没有其他方式设置位图的大小比像素的数量。使用CSS只会改变元素本身的大小,而不是位图,扩展任何绘制到位图以适应元素的大小。

要使用其他单位,你将不得不手动计算这些使用JavaScript,例如:

// using % of viewport for canvas bitmap (pixel ratio not considered) 
var canvas = document.getElementById("myCanvas"), 
    vwWidth = window.innerWidth, 
    vwHeight = window.innerHeight, 
    percent = 60; 

canvas.width = Math.round(vwWidth * percent/100); // integer pixels 
canvas.height = Math.round(vwHeight * percent/100); 

// not to be confused with the style property which affects CSS, ie: 
// canvas.style.width = "60%"; // CSS only, does not affect bitmap 

如果你想支持视网膜,那么你需要使用window.devicePixelRatio与大小相乘。在这种情况下,CSS也是必要的(与上面的代码结合):

var pxRatio = window.devicePixelRatio || 1, 
    width = Math.round(vwWidth * percent/100), 
    height = Math.round(vwHeight * percent/100); 

canvas.width = width * pxRatio; 
canvas.height = height * pxRatio; 

canvas.style.width = width + "px"; 
canvas.style.height = height + "px"; 
+0

非常感谢! – AlonAlon 2014-11-24 20:23:04

0

HTML5中的几乎所有尺寸参数都将以像素为单位。如果您遇到绘图画布与您当前密码的问题,请尝试取得了自闭块结尾:

<canvas id="myCanvas" width="200" height="300"></canvas> 

您也可以考虑观察canvas元素的属性由W3学校的定义: http://www.w3schools.com/html/html5_canvas.asp

0

使用CSS来设置你的画布风格

<canvas id="el"></canvas> 

<style> 

    #el{ 
     display: block; 
     width:100%; 
     height: 100%; 
    }  

</style>