文字基础
context.font = '50px serif';context.fillStyle = '#FF0000';context.fillText('Hello World', 100, 80);
这是最基本的三行代码,第一行不写的话,默认是 10px sans-serif。关于font属性,取值参照CSS的font属性:
[font style] [font weight] [font size] [font face]
比如:context.font = ‘italic bold 24px serif’;
fillText 和 strokeText
fillText就是用 fillStyle 填充整个文字,
而strokeText是用 strokeStyle 对文字进行描边
对齐方式 textBaseline/textAlign
:::info
textBaseline属性用于垂直对齐,它的属性值如下:
:::

const cvs=document.getElementById('test');cvs.width=window.innerWidth;cvs.height=window.innerHeight;const ctx=cvs.getContext('2d');/*辅助线*/ctx.strokeStyle='#999';ctx.setLineDash([8]);ctx.moveTo(30,300);ctx.lineTo(700,300);ctx.stroke();/*font 设置字号字体*/ctx.font="24px Arial";/** textBaseline 文字垂直对齐方式* top:上对其* middle:垂直居中对齐* bottom:下对齐* hanging:悬挂基线对齐* alphabetic:标准字母基线对齐,默认* ideographic:表意文字基线* */ctx.textBaseline='top';ctx.fillText('top',100,300);ctx.textBaseline='middle';ctx.fillText('middle',200,300);ctx.textBaseline='bottom';ctx.fillText('bottom',300,300);ctx.textBaseline='hanging';ctx.fillText('hanging',400,300);ctx.textBaseline='alphabetic';ctx.fillText('alphabetic',500,300);ctx.textBaseline='ideographic';
这里我说下textBaseline的几个属性值:
“alphabetic”:默认值,用于拉丁文或类似的文字。
“ideographic”:用于表意文字,如中文和日文。
“hanging”:用于梵文或类似的文字。
:::info
textAlign属性用于水平对齐
:::
这里的居中只是文本自身的,不是相对于整个canvas,如果想居中于canvas,只需把(x, y)设置为canvas的中心点即可。
文本渐变 createLinearGradient
context.createLinearGradient(x0,y0,x1,y1);//x0 渐变开始点的 x 坐标//y0 渐变开始点的 y 坐标//x1 渐变结束点的 x 坐标//y1 渐变结束点的 y 坐标
如果想在文本上应用渐变,需要注意一点:渐变依赖于定义时的区域,超出这个区域只有纯色,而不是渐变色。
比如文本是这么定义的:context.fillText(‘Text’, 100, 100); 我们希望渐变从(100, 100)开始,结束于文本的右侧,现在我们需要知道文本的宽度。
:::info
这就要用到measureText()方法,它返回一个 TextMetrics 对象,这个对象只有一个width属性。
:::
var text = 'hello canvas';var metrics = context.measureText(text);var textWidth = metrics.width;gradient = context.createLinearGradient(100, 100, textWidth, 100);
案例
<!DOCTYPE html><html lang="en"><head><title></title><style>body {background: #dddddd;}#canvas {margin: 10px;padding: 10px;background: #ffffff;border: thin inset #aaaaaa;}</style></head><body><canvas id='canvas' width='600' height='300'>Canvas not supported</canvas><script >let canvas = document.getElementById('canvas')let context =canvas.getContext('2d');context.font = '38pt Arial';context.fillStyle = 'cornflowerblue';context.strokeStyle = 'blue';// 创建一个渐变var gradient=context.createLinearGradient(0,0,canvas.width,0);gradient.addColorStop("0","magenta");gradient.addColorStop("0.5","blue");gradient.addColorStop("1.0","red");// 填充一个渐变context.fillStyle= gradient;context.fillText("Hello Canvas", canvas.width/2 - 150, canvas.height/2 - 30);context.strokeText("Hello Canvas", canvas.width/2 - 150,canvas.height/2 + 80 );</script></body></html>
