在使用<canvas>元素時必須設置寬度和高度,指定可以繪畫的區域大小。但是這里設置寬度和高度的時候有一個小問題。
樣例代碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>canvas繪圖</title> </head> <body> <canvas id="drawimg" width="300" height="500">A drawimg of something.</canvas> </body> <script> var drawimg=document.getElementById("drawimg"); if(drawimg.getContext){ var context=drawimg.getContext("2d"); context.strokeRect(0, 0, 50, 50); context.fillRect(51, 0, 50, 50); } </script> </html>
在這里我直接在<canvas>標簽內設置了繪畫區域的大小。在瀏覽器中顯示的效果是這樣的
現在我不在標簽內設置寬高。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>canvas繪圖</title>
<style type="text/css"> #drawimg{ width: 300px; height: 500px; }
</style> </head> <body> <canvas id="drawimg" >A drawimg of something.</canvas> </body> <script> var drawimg=document.getElementById("drawimg"); if(drawimg.getContext){ var context=drawimg.getContext("2d"); context.strokeRect(0, 0, 50, 50); context.fillRect(51, 0, 50, 50); } </script> </html>
這時瀏覽器中顯示的效果就成了這樣
結果,原本是寬高一樣矩形,高度明顯拉長了。這是為什么呢?
其實<canvas>有自己的默認寬高300px*150px,而且在<canvas>中定義width、height跟在style中定義width和height是有所區別的,<canvas>標簽的width和height是繪畫區域實際寬度和高度,繪制的圖形都是在這個上面。而style的width和height是<canvas>在瀏覽器中被渲染的高度和寬度。如果<canvas>的width和height沒指定或值不正確,就被設置成默認值{width:300px,height:150px}。
這就解釋了為什么第二種寫法導致圖形被拉伸,繪畫區域的大小沒有在<canvas>中定義,所以設置成立默認的{width:300px,height:150px},而<style>中設置為{width:300px;height:500px;}將繪畫區域的高度拉伸了。