前端analysis | 3w & 1h

《canvas》- canvas doc 学习笔记之文本

2020-05-12

介绍

canvas vs svg

  • canvas 适用于动态创建的位图,缩放失真。
  • svg 适用于静态描述的矢量图,缩放不失真。
  • canvas 基于”状态”绘制图形,譬如,strokeStyle、fillStyle、lineWidth等
  • svg基于dom,可以直接在html中展示

绘图四步骤

  • 定义canvas,设置width,height属性,设置变形等特效
  • 获取canvas 2D context,绘制图形
  • 添加动画
  • 添加交互

canvas w3c坐标系

canvas width\height设置

1
2
3
const dom = document.getElementById('canvas');
dom.width = window.innerWidth;
dom.height = window.innerHeight;
1
<canvas id="canvas" width="600" height="700"></canvas>

canvas 文本

strokeText

1
2
3
4
5
6
const str = '学习hello world';
ctx.font = 'bold 30px 微软雅黑';
# font = "font-style font-weight font-size font-family"

ctx.strokeStyle = 'red';
ctx.strokeText(str,100,100,100);

fillText

1
2
3
4
5
const str = '学习hello world';
ctx.font = 'bold 30px 微软雅黑';

ctx.fillStyle = 'blue';
ctx.fillText(str,200,100,100);

measureText

1
2
3
4
5
6
7
8
const text = ctx.measureText(str);
const width = text.width;

//居中
const canvasWidth = dom.width;
const position = (canvasWidth - width) /2;
ctx.strokeText(str,position,300,100);

textAlign

1
2
 #textAlign 控制文本延伸方向;left/start 向右;right/end向左
ctx.textAlign = 'end';
Tags: canvas
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏