font属性设置或返回画布上文本内容的当前字体属性
var c = document.getElementById('mycanvas');
var ctx = c.getContext('2d');
//context.font="italic small-caps bold 12px arial";
ctx.font = '40px Arial';
ctx.fillText("ecco",20,40);
textAlign属性根据锚点,设置或返回文本内容的当前对齐方式
var c2=document.getElementById("mycanvas2");
var ctx2=c2.getContext("2d");
ctx2.strokeStyle="blue";
ctx2.moveTo(150,20);
ctx2.lineTo(150,170);
ctx2.stroke();
ctx2.font="15px Arial";
ctx2.textAlign="start";
ctx2.fillText("textAlign=start",150,60);
ctx2.textAlign="end";
ctx2.fillText("textAlign=end",150,80);
ctx2.textAlign="left";
ctx2.fillText("textAlign=left",150,100);
ctx2.textAlign="center";
ctx2.fillText("textAlign=center",150,120);
ctx2.textAlign="right";
ctx2.fillText("textAlign=right",150,140);
textBaseline属性设置或返回在绘制文本时的当前文本基线
var c3=document.getElementById("mycanvas3");
var ctx3=c3.getContext("2d");
//Draw a red line at y=100
ctx3.strokeStyle="blue";
ctx3.moveTo(5,100);
ctx3.lineTo(395,100);
ctx3.stroke();
ctx3.font="20px Arial"
ctx3.textBaseline="top";
ctx3.fillText("Top",5,100);
ctx3.textBaseline="bottom";
ctx3.fillText("Bottom",50,100);
ctx3.textBaseline="middle";
ctx3.fillText("Middle",120,100);
ctx3.textBaseline="alphabetic";
ctx3.fillText("Alphabetic",190,100);
ctx3.textBaseline="hanging";
ctx3.fillText("Hanging",290,100);
fillText()方法在画布上绘制填色的文本,文本默认颜色是黑色
请使用 font 属性来定义字体和字号,并使用 fillStyle 属性以另一种颜色/渐变来渲染文本。
var c4 = document.getElementById('mycanvas4');
var ctx4 = c4.getContext('2d');
ctx4.font = '20px Georgia';
ctx4.fillText("AAAAAAAAAAAA",10,50);
ctx4.font = '30px Verdana';
var gradient = ctx4.createLinearGradient(0,0,500,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
ctx4.fillStyle=gradient;
ctx4.fillText("AAAAAAAAAAAAAAAAAAAAAAAAAAAA",10,90);
strokeText()在画布上绘制文本(无填充)
var c5 = document.getElementById('mycanvas5');
var ctx5 = c5.getContext('2d');
ctx5.font = '20px Gerogia';
ctx5.strokeText('AAAAAAAAAAAAAAAAAAA',10,50);
ctx5.font = '30px Verdana';
//创建渐变
var grd5 = ctx5.createLinearGradient(0,0,c5.width,0);
grd5.addColorStop(0,'magenta');
grd5.addColorStop(0.5,'blue');
grd5.addColorStop(1.0,'red');
//用渐变填色
ctx5.strokeStyle = grd5;
ctx5.strokeText('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',10,90);
measureText()方法返回包含一个对象,该对象包含以像素计的指定字体宽度
var c6=document.getElementById("mycanvas6");
var ctx6=c6.getContext("2d");
ctx6.font="30px Arial";
var txt6="Hello World123"
//context.measureText(text).width;
//text : 要测量的文本
ctx6.fillText("width:" + ctx6.measureText(txt6).width,10,50);
ctx6.fillText(txt6,10,100);