返回 导航

HTML5 / CSS3

hangge.com

HTML5 - Canvas的使用样例10(绘制文本)

作者:hangge | 2016-02-04 10:28
1,设置绘图上下文的font属性
(1)设置字体大小(像素)和字体名称
context.font = "22px Arial";

(2)为了适应多个浏览器,字体名字可以多列几种
context.font = "22px Arial,sans-serif";

(3)可以为字体增加加粗效果
context.font = "bold 22px Arial";

2,使用fillText()方法绘制文本内容
文本每次只能绘制一行,如果要绘制多行文本,那只能多次调用fillText()方法。
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

context.font = "bold 22px Arial";
context.textBaseline = "top";
context.fillStyle = "black";
context.fillText("Welcome to hangge.com", 10, 10);

3,使用strokeText()绘制文本轮廓(空心文本)
其中轮廓的颜色取自 strokeStyle 属性,轮廓的宽度取自 lineWidth 属性。
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

context.font = "bold 25px Arial";
context.textBaseline = "top";
context.lineWidth = "1";
context.strokeStyle = "orange";
context.strokeText("Welcome to hangge.com", 10, 10);

4,绘制彩色描边文本
可以先调用 fillText() 绘制实心文本,然后调用 strokeText() 绘制文本的轮廓。
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

context.font = "bold 25px Arial";
context.textBaseline = "top";
context.fillStyle = "black";
context.fillText("Welcome to hangge.com", 10, 10);

context.lineWidth = "1";
context.strokeStyle = "orange";
context.strokeText("Welcome to hangge.com", 10, 10);
评论

全部评论(0)

回到顶部