canvas標籤的width和height以及style.width和style.height的區別

 今天在博問中看到一個問題:用canvas 的 lineto方法畫對角線,但畫出來的圖形不對?

  這是一個很常見的誤區,這裏給大家細說一下。

原理

  在w3網站上是這樣解釋的:

The canvas element has two attributes to control the size of the coordinate space: width and height. These attributes, when specified, must have values that are valid non-negative integersThe rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

  其實這裏已經說的很明白,通俗點說就是在canvas中定義width、height跟在style中定義width和height是不同的,canvas標籤的width和height是畫布實際寬度和高度,繪製的圖形都是在這個上面。而style的width和height是canvas在瀏覽器中被渲染的高度和寬度。如果canvas的width和height沒指定或值不正確,就被設置成默認值(width:300px,height:150px)。

  我們可以利用style的width和height來縮放canvas,請看下面的示例。

示例

  示例代碼如下:

<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function drawDiagonal(id){
var canvas=document.getElementById(id);
var context=canvas.getContext("2d");
context.beginPath();
context.moveTo(
0,0);
context.lineTo(
100,100);
context.stroke();
}

window.onload
=function(){
drawDiagonal(
"diagonal1");
drawDiagonal(
"diagonal2");
drawDiagonal(
"diagonal3");
}
</script>
</head>
<body>
<canvas id="diagonal1" style="border:1px solid;" width="100px" height="100px"></canvas>
<canvas id="diagonal2" style="border:1px solid;width:200px;height:200px;" width="100px" height="100px"></canvas>
<canvas id="diagonal3" style="border:1px solid;width:200px;height:200px;"></canvas>
</body>
</html>

  運行效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章