Canvas文本

Canvas文本

文本API

使用Canvas显示字体分下面三步:

  • 使用font设置字体;
  • 使用fillStyle设置字体颜色;
  • 使用fillText()方法显示字体;

默认情况下font属性可以不指定,如果不指定字体,则默认使用10px无衬字体;贴上一个例子:

1
2
3
4
5
6
7
8
9
10
11
window.onload = function() {
let canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 600;

let context = canvas.getContext("2d");

context.font = "50px serif";
context.fillStyle = "#00AAAA";
context.fillText("Canvas -- Draw on the web", 50, 300);
};

文本渲染

和图形一样,文本也提供了fillText()strokeText()两种方法。具体看例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
window.onload = function() {
let canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 600;

let context = canvas.getContext("2d");

context.beginPath();
context.font = "50px Verdana";
var gradient = context.createLinearGradient(0, 0, 800, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");

context.fillStyle = gradient;
context.strokeStyle = "#00AAAA";
context.strokeText("Text", 50, 100);
context.fillText("Text", 50, 100);

context.fillText("Text", 50, 300, 200);
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!