Canvas fillText方法详解,掌握文本填充绘制、最大宽度限制、渐变文本等技巧。fillText方法在Canvas上绘制填充文本,是最常用的文本绘制方式。
ctx.fillText(text, x, y, maxWidth)
| 参数 | 说明 |
|---|---|
| text | 要绘制的文本 |
| x | 起始X坐标 |
| y | 起始Y坐标(基线位置) |
| maxWidth | 可选,最大宽度 |
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
ctx.font = '30px Arial'
ctx.fillStyle = '#3498db'
ctx.fillText('Hello Canvas', 50, 100)
当指定maxWidth时,文本会自动缩放以适应宽度。
ctx.font = '30px Arial'
// 无宽度限制
ctx.fillText('Hello World', 50, 50)
// 限制最大宽度
ctx.fillText('Hello World', 50, 100, 100)
使用渐变作为fillStyle创建渐变文本效果。
const gradient = ctx.createLinearGradient(0, 0, 200, 0)
gradient.addColorStop(0, '#e74c3c')
gradient.addColorStop(0.5, '#f39c12')
gradient.addColorStop(1, '#2ecc71')
ctx.font = '40px Arial'
ctx.fillStyle = gradient
ctx.fillText('渐变文本', 50, 100)
使用图案作为填充样式。
结合shadow属性创建阴影效果。
字体设置
必须先设置font属性才能正确绘制文本。
基线位置
y坐标是文本基线位置,不是顶部。
换行处理
fillText不支持自动换行,需要手动处理多行文本。
function drawMultiLineText(ctx, text, x, y, lineHeight) {
const lines = text.split('\n')
lines.forEach((line, i) => {
ctx.fillText(line, x, y + i * lineHeight)
})
}