canvas提供两种文本渲染方式:

fillText(text,x,y[,maxWidth]);	// 在指定的(x,y)处填充文本,绘制的最大宽度是可选的
strokeText(text,x,y[,maxWidth]);	// 在指定的(x,y)处绘制文本边框,绘制的最大宽度是可选的

属性:

font = value;	// 当前绘制文本的样式,和使用css中font属性相同,默认是"10px sans-serif"
textAlign = value;	// 文本对齐选项,可选值:start、end、left、right、center,默认值为start
textBaseline = value;	// 基线对齐选项,可选值:top、hanging、middle、alphabetic、ideographic、bottom,默认值为alphabetic
direction = value;	// 文本方向,可选值:ltr、rtl、inherit,默认值为inherit

canvas中绘制文本

预测量文本宽度:

measureText();	// 将返回一个TextMetrics对象的宽度、所在的像素等体现文本特性的属性

例如:

let cvs = document.getElementById("cvs");
let ctx = cvs.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.font = "48px serif";	
let txt = "measureText";
ctx.measureText(txt).width;

ctx.fillText(ctx.measureText(txt).width,80,100);
ctx.fillText(txt,80,130);

效果:
canvas中绘制文本

参考地址:

http://www.w3school.com.cn/html5/canvas_textbaseline.asp
https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial/Drawing_text

相关文章:

  • 2022-01-11
  • 2021-06-14
  • 2022-12-23
  • 2021-12-05
  • 2022-01-22
  • 2022-12-23
  • 2021-12-02
猜你喜欢
  • 2021-11-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-14
  • 2021-04-27
  • 2022-12-23
相关资源
相似解决方案