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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM