2014-11-23 100 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>