绘制文字
1.控制文本的字体、大小和样式
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>4.7.1.html</title> 6 </head> 7 <body> 8 <canvas id="myCanvas" width="400" height="400">您的浏览器不支持canvas标签</canvas> 9 <script type="text/javascript"> 10 var c=document.getElementById("myCanvas"); 11 var ctx=c.getContext("2d"); 12 ctx.font="italic small-caps bold 50px Arial"; 13 ctx.fillText("Hello! Canvas",10,50); 14 </script> 15 </body> 16 </html>
2.控制文本的颜色
两种方式:一通过fillStyle函数设置文本的填充颜色,另一种是通过createLinearGradient函数为文字填充渐变色:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>4.7.2.html</title> 6 </head> 7 <body> 8 <canvas id="myCanvas" width="400" height="400">您的浏览器不支持canvas标签</canvas> 9 <script type="text/javascript"> 10 var c=document.getElementById("myCanvas"); 11 var ctx=c.getContext("2d"); 12 //创建单色字体 13 ctx.font="50px Georgia"; 14 ctx.fillStyle="blue"; 15 ctx.fillText("Hello Canvas!",10,50); 16 //创建渐变字体 17 ctx.font="50px Verdana"; 18 var gradient=ctx.createLinearGradient(0,0,c.width,0); 19 gradient.addColorStop("0","magenta"); 20 gradient.addColorStop("0.5","blue"); 21 gradient.addColorStop("1.0","red"); 22 ctx.fillStyle=gradient; 23 ctx.fillText("Hello Canvas!",10,90); 24 </script> 25 </body> 26 </html>
3.描绘文本的边缘
使用strokeText函数代替fillText函数,同时要用strokeStyle属性替代fillStyle属性,描绘文本边缘:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>4.7.3.html</title> 6 </head> 7 <body> 8 <canvas id="myCanvas" width="400" height="400">您的浏览器不支持canvas标签</canvas> 9 <script type="text/javascript"> 10 var c=document.getElementById("myCanvas"); 11 var ctx=c.getContext("2d"); 12 ctx.font="50px Verdana"; 13 // 创建渐变 14 var gradient=ctx.createLinearGradient(0,0,c.width,0); 15 gradient.addColorStop("0","magenta"); 16 gradient.addColorStop("0.5","blue"); 17 gradient.addColorStop("1.0","red"); 18 // 用渐变填色 19 ctx.strokeStyle=gradient; 20 ctx.strokeText("Hello Canvas!",10,90); 21 </script> 22 </body> 23 </html>
4.设置文本对齐方式
Canvas中文本的对齐功能使用textAlign属性进行控制,可提供选择的选项包括start、end、left、center 和right。对齐的位置是相对于一条虚拟的垂直线,有fillText()或strokeText()定义的文本x的位置。
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>4.7.4.html</title> 6 </head> 7 <body> 8 <canvas id="myCanvas" width="400" height="400">您的浏览器不支持canvas标签</canvas> 9 <script type="text/javascript"> 10 var c=document.getElementById("myCanvas"); 11 var ctx=c.getContext("2d"); 12 var x = c.width / 2; 13 var y = c.height / 2; 14 ctx.font = "30pt Calibri"; 15 ctx.textAlign = "center"; 16 ctx.fillStyle = "blue"; 17 ctx.fillText("Hello Canvas!", x, y); 18 </script> 19 </body> 20 </html>