首页 / HTML5 入门教程 / Canvas 文本与样式

HTML5 入门教程

Canvas 文本与样式

本教程共 110 篇 · 第 83 篇 · 更新于 2026-07-28 · 约 4 分钟阅读

HTML5HTML5 入门教程Canvas文本字体渐变阴影

83. Canvas 文本与样式

本节目标:学会在 Canvas 上绘制文字,掌握字体、颜色、阴影和渐变的设置方法。

画布不只能画图形,还能写文字。Canvas 提供了几个绘制文本的方法,配合样式设置,效果很丰富。

绘制文本

填充文字

fillText(text, x, y) 在指定位置绘制填充文字:

ctx.font = '24px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 50, 50);

空心文字

strokeText(text, x, y) 只画文字轮廓:

ctx.font = '30px Arial';
ctx.strokeStyle = 'blue';
ctx.lineWidth = 1;
ctx.strokeText('空心文字', 50, 100);

文字对齐

属性说明
textAlignleft / center / right水平对齐
textBaselinetop / middle / bottom垂直对齐
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('居中文字', 200, 100);

字体设置

font 属性的语法和 CSS 的 font 属性类似:

ctx.font = 'bold 36px 微软雅黑';
ctx.fillText('加粗大字', 50, 80);

格式通常是:[样式] 大小 字体族。样式可以是 bolditalicbold italic

阴影效果

Canvas 支持给图形和文字加阴影:

ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.shadowBlur = 10;        // 模糊程度
ctx.shadowOffsetX = 5;      // X 偏移
ctx.shadowOffsetY = 5;      // Y 偏移

ctx.font = '30px Arial';
ctx.fillStyle = 'black';
ctx.fillText('带阴影的文字', 50, 100);
Tip

阴影会影响后续所有绘制。不需要阴影时,把 shadowBlur 设为 0 或 shadowColor 设为 transparent

渐变填充

Canvas 支持两种渐变:线性渐变和径向渐变。

线性渐变

// 创建渐变对象
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');    // 起点颜色
gradient.addColorStop(0.5, 'yellow'); // 中间颜色
gradient.addColorStop(1, 'blue');   // 终点颜色

ctx.fillStyle = gradient;
ctx.fillRect(50, 50, 200, 100);

createLinearGradient(x1, y1, x2, y2) 定义渐变方向。上面的例子是从左到右。

径向渐变

const gradient = ctx.createRadialGradient(100, 100, 10, 100, 100, 80);
gradient.addColorStop(0, 'white');
gradient.addColorStop(1, 'blue');

ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 2);
ctx.fill();

createRadialGradient(x1, y1, r1, x2, y2, r2) 定义两个圆,从内圆向外圆渐变。

透明度

globalAlpha 设置全局透明度,取值 0 到 1:

ctx.globalAlpha = 0.5; // 半透明
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);

ctx.globalAlpha = 1; // 恢复不透明

绘制图片

Canvas 还能把图片画到画布上:

const img = new Image();
img.src = 'photo.jpg';
img.onload = function() {
  ctx.drawImage(img, 50, 50, 200, 150);
};

drawImage 有三种用法:

用法说明
drawImage(img, x, y)原尺寸绘制
drawImage(img, x, y, w, h)缩放到指定尺寸
drawImage(img, sx, sy, sw, sh, x, y, w, h)裁剪并绘制
Note

图片加载是异步的,必须在 onload 回调里绘制,否则画不出来。

完整示例

// 背景渐变
const bg = ctx.createLinearGradient(0, 0, 0, 300);
bg.addColorStop(0, '#87CEEB');
bg.addColorStop(1, '#E0F6FF');
ctx.fillStyle = bg;
ctx.fillRect(0, 0, 400, 300);

// 带阴影的文字
ctx.shadowColor = 'rgba(0,0,0,0.3)';
ctx.shadowBlur = 5;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.font = 'bold 28px Arial';
ctx.fillStyle = '#333';
ctx.textAlign = 'center';
ctx.fillText('Canvas 文字效果', 200, 150);

小结

  • fillText 画填充文字,strokeText 画空心文字
  • font 属性设置字体样式
  • shadowColorshadowBlurshadowOffsetX/Y 设置阴影
  • createLinearGradientcreateRadialGradient 创建渐变
  • globalAlpha 控制透明度
  • drawImage 把图片绘制到画布上