canvas的fillText參數解釋


一開始用filleText總是顯示不出來文字,很是郁悶,后來琢磨了下,原來fillText常用的三個參數的意思弄錯了。

void fillText(DOMString text, double x, double y, optional double maxWidth);

 常用的形式是 fillText("要現實的文字",x,y),注意這里面的x,y代表的是哪個點的坐標。

例子如下

 1 <!DOCTYPE html> <html>
2 <head>
3 <script type="text/javascript">
4
5 //fillText的后兩個參數是 text的左下角那個點坐標,而不是text的左上
6 //角點坐標
7
8 function addText()
9 {
10 var c = document.getElementById("mycanvas");
11 //console.log( c );
12 var ctx = c.getContext("2d");
13
14 ctx.moveTo(10,100);
15 ctx.lineTo(200,100);
16 ctx.stroke();
17 ctx.fillText('nihao',10,100);
18
19 }
20
21 </script>
22 </head>
23
24 <body onload="addText()">
25 <canvas id="mycanvas" width="600" height="500">
26 Your boswer is not support the canvas element.
27 </canvas>
28 </body>
29 </html>

輸出截圖如下:

可以發現,后面的x,y參數其實是文字左下角的那個點的坐標。

所以如果代碼改動如下時,什么文字都不會顯示出來。

    ctx.moveTo(10,100);//不變
ctx.lineTo(200,100);//不變
ctx.stroke();//不變
ctx.fillText('nihao',10,0);//原來的代碼是 ctx.fillText('nihao',10,100),即改動了y坐標的值
 
        

想想為什么呢?

因為fillText的基線(textBaseline)就在坐標y=0的點上,而文字要寫在基線之上,自然就超出canvas的上邊界了,所以在canvas里什么也沒有顯示。

 

-----------------------------------------------------------------------------------------------

參考:

關於fillText的使用及實例請參考一下兩個鏈接:

1.How to display text in canvas(比較全面)

http://www.html5tutorial.info/html5-canvas-text.php (英文)

2.同時,也可以參考園子里一個寫的很好的中文博客:

http://www.cnblogs.com/zhujl/archive/2012/02/10/2345554.html

 

想了解更多:

關於fillText的詳細參數請參閱官網:http://www.whatwg.org/specs/web-apps/current-work/


免責聲明!

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



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