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/

原文地址:https://www.cnblogs.com/muyun/p/2353506.html