返回
文本绘画:fillText() 和 strokeText()
前端
2023-11-28 09:51:52
引言:
在深入探讨 Canvas 的世界时,我们不可避免地会遇到文本绘制的艺术。绘制文本使我们能够在我们的画布上添加标签、标题和信息,从而为我们的用户提供指导并增强交互性。在 Canvas 中,有两种主要的方法可以实现文本绘制:fillText() 和 strokeText()。
fillText():
fillText() 方法在指定位置绘制一个填充文本的轮廓。它使用 currentFillStyle 属性定义的颜色来填充文本。语法如下:
fillText(text, x, y)
其中:
- text :要绘制的文本字符串
- x :文本起始点的 X 坐标
- y :文本起始点的 Y 坐标
strokeText():
strokeText() 方法与 fillText() 类似,但它不填充文本轮廓。相反,它使用 currentStrokeStyle 属性定义的颜色绘制文本轮廓。语法如下:
strokeText(text, x, y)
与 fillText() 相同的参数适用于 strokeText()。
文本样式:
fillText() 和 strokeText() 方法还支持一系列文本样式属性,允许我们控制文本的外观。这些属性包括:
- font :定义字体族、大小和样式
- textAlign :指定文本的对齐方式(左对齐、居中或右对齐)
- textBaseline :指定文本基线的位置(顶部、中间或底部)
示例:
以下代码段演示了如何在 Canvas 中使用 fillText() 和 strokeText() 绘制文本:
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// 使用 fillText() 绘制填充文本
ctx.fillStyle = "blue";
ctx.font = "30px Arial";
ctx.fillText("这是使用 fillText() 绘制的文本", 100, 100);
// 使用 strokeText() 绘制轮廓文本
ctx.strokeStyle = "red";
ctx.font = "20px Verdana";
ctx.strokeText("这是使用 strokeText() 绘制的文本", 200, 150);
结论:
fillText() 和 strokeText() 是在 Canvas 中绘制文本的基本方法。通过了解这两种方法及其文本样式属性,我们可以创建各种引人注目的文本效果,增强我们的 Canvas 应用程序的用户体验。