绘制渐变

 

概述

Canvas API中提供设置渐变色的方法有:

  • createLinearGradient:线性渐变
  • createRadialGradient:径向渐变

代码示例

线性渐变

CanvasRenderingContext2D.createLinearGradient(x0, y0, x1, y1);
CanvasGradient.addColorStop(position, color);
  • x0:渐变开始点x坐标
  • y0:渐变开始点y坐标
  • x1:渐变结束点x坐标
  • y1:渐变结束点y坐标
  • position:设定的颜色离渐变结束点的偏移量(0~1)
  • color:绘制时使用的颜色

GridFunny定义与abstract一节中一致

// GridFunny定义 
var grid = new GridFunny({
    onDraw: function() {
        var num = this.settings.gridNum,
            gradient = this.context.createLinearGradient(0, 0, 0, this.pixelY * num);
        gradient.addColorStop(0, 'red');
        gradient.addColorStop(0.5, 'green');
        gradient.addColorStop(1, 'blue');
        this.context.fillStyle = gradient;
        this.context.fillRect(this.gridOfX[1], this.gridOfY[1], this.pixelX * num, this.pixelY * num);
    }
});
grid.start();

以下是代码的执行效果:

径向渐变(发散)

CanvasRenderingContext2D.createRadialGradient(x0, y0, r0, x1, y1, r1)
CanvasGradient.addColorStop(position, color);
  • x0:发散开始圆心x坐标
  • y0:发散开始圆心y坐标
  • r0:发散开始圆的半径
  • x1:发散结束圆心的x坐标
  • y1:发散结束圆心的y坐标
  • r1:发散结束圆的半径
  • position:设定的颜色离渐变结束点的偏移量(0~1)
  • color:绘制时使用的颜色

GridFunny定义与abstract一节中一致

// GridFunny定义 
var grid = new GridFunny({
    nextDraw: function() {
        var num = this.settings.gridNum,
            canvasSize = this.settings.canvasSize,
            cX = canvasSize.width / 2,
            cY = canvasSize.height / 2,
            gradient = this.context.createRadialGradient(cX,cY, 20, cX, cY, 110);
        gradient.addColorStop(0, 'yellow');
        gradient.addColorStop(1, 'green');
        this.context.fillStyle = gradient;
        this.context.beginPath();
        this.context.arc(cX, cY, 110, 0, 2 * Math.PI, false);
        this.context.fill();
        this.context.closePath();
    }
});
grid.start();

以下是代码的执行效果: