createLinearGradient() 简介

createLinearGradient() 是 Canvas 2D 上下文中用于创建线性渐变的方法。它沿着一条直线方向,在两个或多个颜色之间平滑过渡。

语法

const gradient = ctx.createLinearGradient(x0, y0, x1, y1);
参数 说明
x0, y0 渐变的起点坐标
x1, y1 渐变的终点坐标

基本使用流程

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// 第一步:创建渐变对象
const gradient = ctx.createLinearGradient(0, 0, 200, 0);  // 水平渐变

// 第二步:添加颜色节点(0~1之间的位置)
gradient.addColorStop(0, '#ff0000');     // 起始位置:红色
gradient.addColorStop(0.5, '#00ff00');   // 中间位置:绿色
gradient.addColorStop(1, '#0000ff');     // 结束位置:蓝色

// 第三步:将渐变赋值给 fillStyle 或 strokeStyle
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 200);

渐变方向示例

// 水平渐变(从左到右)
const hGrad = ctx.createLinearGradient(0, 0, 200, 0);

// 垂直渐变(从上到下)
const vGrad = ctx.createLinearGradient(0, 0, 0, 200);

// 对角线渐变
const dGrad = ctx.createLinearGradient(0, 0, 200, 200);

完整示例:彩虹渐变矩形

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// 创建从左上到右下的渐变
const grad = ctx.createLinearGradient(0, 0, 300, 250);

// 添加多个颜色节点
grad.addColorStop(0, '#ff0000');     // 红
grad.addColorStop(0.16, '#ff8800');  // 橙
grad.addColorStop(0.33, '#ffff00');  // 黄
grad.addColorStop(0.49, '#00ff00');  // 绿
grad.addColorStop(0.66, '#0088ff');  // 蓝
grad.addColorStop(0.83, '#0000ff');  // 靛
grad.addColorStop(1, '#8800ff');     // 紫

ctx.fillStyle = grad;
ctx.fillRect(0, 0, 300, 250);

注意事项

  1. 坐标是相对于画布的,不是相对于绘制图形的起始位置
  2. 超出渐变范围的区域:起点之前的区域使用第一个颜色,终点之后的区域使用最后一个颜色
  3. addColorStop() 的位置参数必须在 0 ~ 1 之间
  4. 可以添加任意多个颜色节点,实现复杂的渐变效果

应用场景

  • 按钮背景
  • 进度条填充
  • 图表渐变色
  • 背景装饰
  • 文字描边渐变
// 文字渐变示例
ctx.font = 'bold 48px Arial';
ctx.strokeStyle = gradient;  // 或者 fillStyle = gradient
ctx.strokeText('Hello', 50, 100);