答案:在Canvas上绘制文本需获取2D上下文,设置字体、颜色、对齐方式和基线后,调用fillText()或strokeText()方法绘制;为确保跨设备一致性,应处理设备像素比、字体加载和Canvas尺寸管理;换行需借助measureText()手动计算,溢出可加省略号;复杂效果如阴影、渐变可通过shadow属性和createLinearGradient实现,结合fillText与strokeText可增强视觉表现。

要在Canvas上绘制文本,核心就是利用2D渲染上下文(context)的
fillText()
strokeText()
具体怎么操作呢?我们来一步步看。首先,你需要获取到Canvas元素的2D渲染上下文。这是所有绘图操作的入口。接着,设置好你想要的字体样式、颜色、以及文本的对齐方式和基线。最后,调用
fillText()
strokeText()
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 清空画布,以便每次重绘时看到最新效果
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 1. 设置字体样式
// 格式通常是 "font-weight font-size font-family"
ctx.font = '48px Arial';
// 我个人比较喜欢用像素作为单位,因为它在Canvas上最直接。
// 但要注意,这里是CSS的font属性,所以你可以用所有CSS支持的字体值。
// 2. 设置填充颜色 (用于fillText)
ctx.fillStyle = '#333'; // 深灰色
// 3. 设置文本对齐方式
// 'start', 'end', 'left', 'right', 'center'
// 我发现'center'在很多场景下非常实用,可以把文本精准定位到某个中心点。
ctx.textAlign = 'center';
// 4. 设置文本基线
// 'alphabetic' (默认), 'top', 'hanging', 'middle', 'ideographic', 'bottom'
// 'middle'和'alphabetic'是我最常用的,'middle'对于垂直居中很有帮助。
ctx.textBaseline = 'middle';
// 5. 绘制填充文本
// 参数:文本内容, x坐标, y坐标, [最大宽度,可选]
ctx.fillText('Hello Canvas Text!', canvas.width / 2, canvas.height / 2);
// 如果你想绘制描边文本,可以这样做:
ctx.font = '36px sans-serif';
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2; // 描边宽度
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.strokeText('描边文本', 50, 50);
// 你也可以结合使用填充和描边
ctx.font = '60px Impact';
ctx.fillStyle = 'orange';
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.textAlign = 'center';
ctx.textBaseline = 'alphabetic';
ctx.fillText('混合效果', canvas.width / 2, canvas.height - 100);
ctx.strokeText('混合效果', canvas.width / 2, canvas.height - 100);在使用
fillText()
strokeText()
x
y
textAlign
textBaseline
当然,仅仅是画出来还不够。实际项目中,我们经常会遇到一个问题:为什么我的Canvas文本在我的高分屏上看起来模糊,或者在别人的电脑上字体大小不对?确保Canvas文本在不同设备上显示一致,这确实是个值得深入探讨的话题。
首先,设备像素比(Device Pixel Ratio)是一个大头。在Retina屏或者其他高DPI设备上,一个CSS像素可能对应多个物理像素。如果你直接按
canvas.width
canvas.height
window.devicePixelRatio
const dpr = window.devicePixelRatio || 1; canvas.width = originalWidth * dpr; canvas.height = originalHeight * dpr; ctx.scale(dpr, dpr); // 缩放上下文,让后续绘制操作仍然使用逻辑像素 // CSS 样式控制显示尺寸 canvas.style.width = originalWidth + 'px'; canvas.style.height = originalHeight + 'px';
其次,字体加载。如果你使用了自定义的Web字体(比如Google Fonts),一定要确保字体在Canvas绘制之前已经完全加载。Canvas在绘制时如果字体还没加载好,它会回退到默认字体,这就会导致文本大小、布局完全错位。我通常会用
document.fonts.ready
// 确保字体加载后再绘制
document.fonts.ready.then(() => {
// 字体加载完成,现在可以安全地绘制Canvas文本了
drawTextOnCanvas();
}).catch(err => {
console.error('字体加载失败:', err);
// 即使失败,也尝试用默认字体绘制
drawTextOnCanvas();
});最后,Canvas自身的尺寸管理。确保你设置
canvas.width
canvas.height
canvas.width
canvas.height
处理好一致性之后,文本的布局又是另一个挑战,尤其是当内容很长的时候。Canvas本身并没有内置的文本换行功能,这确实有点让人头疼,意味着我们得手动实现。但别担心,
measureText()
我的通用思路是这样的:
ctx.measureText(currentLine + word).width
y
fontSize * 1.2
function wrapText(ctx, text, x, y, maxWidth, lineHeight) {
const words = text.split(' '); // 通常按空格分割词语
let line = '';
let testLine = '';
let metrics;
for (let n = 0; n < words.length; n++) {
testLine = line + words[n] + ' ';
metrics = ctx.measureText(testLine);
const testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
ctx.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
} else {
line = testLine;
}
}
ctx.fillText(line, x, y); // 绘制最后一行
}
// 示例调用
ctx.font = '20px sans-serif';
ctx.fillStyle = 'black';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
const longText = "这是一段非常长的文本,用来演示在Canvas中如何进行文本的自动换行处理,这需要我们手动计算每一行的宽度并决定何时开始新的一行。";
wrapText(ctx, longText, 50, 150, 300, 25); // x=50, y=150, maxWidth=300, lineHeight=25对于溢出处理,如果文本行数过多,超出了预设的区域,你可能需要添加省略号(
...
wrapText
...
...
maxWidth
measureText()
文本不仅仅是信息载体,它也可以是艺术的一部分。Canvas提供了不少工具,让我们能给文本加上一些“特效”,让它看起来更酷,更有表现力。
1. 文本阴影 给文本添加阴影非常简单,你只需要设置
ctx.shadowColor
ctx.shadowOffsetX
ctx.shadowOffsetY
ctx.shadowBlur
ctx.font = '70px "Comic Sans MS"';
ctx.fillStyle = 'purple';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'; // 阴影颜色
ctx.shadowOffsetX = 5; // X轴偏移
ctx.shadowOffsetY = 5; // Y轴偏移
ctx.shadowBlur = 8; // 模糊半径
ctx.fillText('带阴影的文本', canvas.width / 2, canvas.height / 2 + 100);
// 注意:阴影属性会影响后续所有绘制,如果不需要,记得重置它们
ctx.shadowColor = 'transparent';
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = 0;2. 文本渐变 让文本拥有渐变色,这能让它瞬间提升一个档次。你需要先创建一个渐变对象(线性或径向),然后把这个渐变对象赋值给
ctx.fillStyle
ctx.strokeStyle
// 创建一个线性渐变
const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0); // 从左到右
gradient.addColorStop(0, 'red');
gradient.addColorStop(0.5, 'yellow');
gradient.addColorStop(1, 'blue');
ctx.font = '80px Impact';
ctx.fillStyle = gradient; // 将填充样式设置为渐变
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('渐变文本', canvas.width / 2, canvas.height / 2 - 100);3. 描边与填充结合 前面也提到了,你可以先
fillText()
strokeText()
ctx.font = '90px "Arial Black"';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// 填充部分
ctx.fillStyle = 'lime';
ctx.fillText('酷炫文字', canvas.width / 2, canvas.height / 2);
// 描边部分
ctx.strokeStyle = 'darkgreen';
ctx.lineWidth = 4;
ctx.strokeText('酷炫文字', canvas.width / 2, canvas.height / 2);记住,每次改变样式(如
fillStyle
strokeStyle
lineWidth
ctx.save()
ctx.restore()
save()
restore()
以上就是canvas如何绘制文本的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号