Canvas中createLinearGradient画不出渐变,主因是坐标系理解错误、变换干扰、色标offset超范围(须0–1)、未适配devicePixelRatio及resize后未更新渐变坐标。
createLinearGradient 画不出渐变?先看坐标系是否搞反了Canvas 的渐变不是“从颜色 A 到颜色 B”就完事,它严格依赖起点 (x0, y0) 和终点 (x1, y1) 构成的线段方向。常见错误是以为 createLinearGradient(0, 0, 100, 0) 就是“从左到右”,但实际效果取决于你 fillRect 的位置和 canvas 坐标系原点(左上角)。如果画布没重置、或用 transform 移动过,起点/终点坐标可能被意外偏移。
0, 0, canvas.width, 0 表示横向全宽渐变)createLinearGradient 前使用 ctx.save()/c
tx.translate() 等变换,除非你明确知道它们会影响渐变线段坐标ctx.strokeStyle = 'red'; ctx.beginPath(); ctx.moveTo(x0,y0); ctx.lineTo(x1,y1); ctx.stroke(); 画出渐变轴线,确认方向是否符合预期addColorStop,且 offset 必须在 0–1 范围内addColorStop 的第一个参数是归一化偏移量(0.0 到 1.0),不是像素值。很多人写成 grad.addColorStop(50, '#f00') 或 grad.addColorStop(-0.1, '#000'),结果静默失败——浏览器不会报错,但该色标直接被忽略,导致渐变断层或单色填充。
0 和 1),否则渐变无效addColorStop(0.5, '#f00'); addColorStop(0.5, '#00f');)const grad = ctx.createLinearGradient(0, 0, 200, 0); grad.addColorStop(0, '#ff9a9e'); // 左端 grad.addColorStop(0.5, '#fad0c4'); // 中间 grad.addColorStop(1, '#a1c4fd'); // 右端 ctx.fillStyle = grad; ctx.fillRect(0, 0, 200, 100);
createLinearGradient 返回的是一个 CanvasGradient 对象,它本身不绑定画布尺寸或绘制内容,只要坐标逻辑合理,完全可以复用。问题常出在:你在 canvas resize 后没更新渐变坐标,却还用旧的 grad 对象,导致渐变拉伸变形或偏移。
(x0,y0,x1,y1)
ctx.fillStyle = grad 写在初始化阶段,而应在每次绘制前设置,避免因上下文状态残留导致意外覆盖某些 iOS Safari 版本对带 transform: scale() 的 canvas 容器中渲染渐变有 bug;更常见的是高 DPI 设备(如 Retina 屏)下,若 canvas 的 width/height 属性没按 devicePixelRatio 缩放,而 CSS 样式又设置了 width: 100%; height: 100%,会导致渐变坐标被拉伸,看起来像“只显示一半”或“颜色挤在一起”。
width 和 height 属性(不是 CSS 样式),并乘以 window.devicePixelRatio
transform,改用 position + top/left 控制位置console.log(ctx.fillStyle) 看是否仍为 CanvasGradient 实例,排除被意外覆盖成字符串颜色的可能addColorStop 不代表能稳定出图。