Appearance
渐变
线性渐变
实际上画笔是CanvasRenderingContext2D对象。在它下面有CanvasGradient,可以用于绘制线性渐变图像。
javascript
// 创建渐变
const gradient = ctx.createLinearGradient(0,0,600,400);
// 开始渐变
gradient.addColorStop(0, 'red');
// 结束渐变
gradient.addColorStop(1, 'blue');
ctx.moveTo(0,0);
ctx.lineTo(400,400);
ctx.lineWidth = 20;
// 渐变作为线条颜色
ctx.strokeStyle = gradient;
ctx.stroke();
径向渐变
createRadialGradient(x0,y0,r0, x1,y1,r1)
实际上是要分别确定两个圆的x,y坐标和半径r。
javascript
const gradient = ctx.createRadialGradient(100,100,0,100,100,100)
gradient.addColorStop(0, 'red')
gradient.addColorStop(1, 'green')
ctx.fillStyle = gradient;
ctx.fillRect(0,0,200,200);
锥形渐变
createConicGradient(startAngle, x, y)
这里的startAngle是弧度制的。换算成角度的话是:
startAngle * (Math.PI / 180)
javascript
const gradient = ctx.createConicGradient(0, 100, 100);
gradient.addColorStop(0, "red");
gradient.addColorStop(0.25, "orange");
gradient.addColorStop(0.5, "yellow");
gradient.addColorStop(0.75, "green");
gradient.addColorStop(1, "blue");
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 200, 200);