canvas標(biāo)簽的width和height以及style.width和style.height的區(qū)別
背景
今天在博問中看到一個(gè)問題:用canvas 的 lineto方法畫對角線,但畫出來的圖形不對?
這是一個(gè)很常見的誤區(qū),這里給大家細(xì)說一下。
原理
在w3網(wǎng)站上是這樣解釋的:
The
canvaselement has two attributes to control the size of the coordinate space:widthandheight. These attributes, when specified, must have values that are valid non-negative integers. The 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. Thewidthattribute defaults to 300, and theheightattribute defaults to 150.The intrinsic dimensions of the
canvaselement 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.
其實(shí)這里已經(jīng)說的很明白,通俗點(diǎn)說就是在canvas中定義width、height跟在style中定義width和height是不同的,canvas標(biāo)簽的width和height是畫布實(shí)際寬度和高度,繪制的圖形都是在這個(gè)上面。而style的width和height是canvas在瀏覽器中被渲染的高度和寬度。如果canvas的width和height沒指定或值不正確,就被設(shè)置成默認(rèn)值(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>

作者:Artwl
本文首發(fā)博客園,版權(quán)歸作者跟博客園共有。轉(zhuǎn)載必須保留本段聲明,并在頁面顯著位置給出本文鏈接,否則保留追究法律責(zé)任的權(quán)利。
浙公網(wǎng)安備 33010602011771號