# ctx.gradient()

[browser](../../../..) ⟩ [canvas](../../..) ⟩ [gradient]() ⟩ ctx.gradient()

{% tabs %}
{% tab title="💾 程式" %}
:floppy\_disk: replit: [canvas gradients](https://replit.com/@pegasusroe/canvas-gradients#script.js)

```javascript
// ⭐ ctx.gradient()
CanvasRenderingContext2D.prototype.gradient = function(type, args, stops){
    
    const methodName = 'CanvasRenderingContext2D.prototype.gradient';
    
    if (!stops || !Array.isArray(stops) || stops.length < 2) 
        throw new Error(`⛔ ${methodName}: needs at least two color stops.`);
    
    // create gradient
    let gradient;
    
    switch (type) {
        case 'linear': gradient = this.createLinearGradient(...args); break;
        case 'radial': gradient = this.createRadialGradient(...args); break;
        case 'conic' : gradient = this.createConicGradient(...args); break;
        default: throw new Error(`⛔ ${methodName}: gradient type "${type}" is not one of "linear" | "radial" | "conic".`)
    }

    // add color stops
    stops.forEach(([offset, color]) => gradient.addColorStop(offset, color));
    
    // return gradient object
    return gradient;
};
```
{% endtab %}

{% tab title="💈範例" %}
![linear (left), radial/conic (right)](https://2527454625-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MfvEFZnSBhKT6fJmus0%2Fuploads%2FWf5mzdMLRYbrsMFUzpFf%2Fcanvas%20gradients.png?alt=media\&token=b47534d5-243d-427e-8227-7b7314eda6ed)

:floppy\_disk: replit: [canvas gradients](https://replit.com/@pegasusroe/canvas-gradients#script.js)

⬆️ 需要： [drawoncanvas2d](../../../+ext/drawoncanvas2d "mention")

```javascript
const { PI: pi } = Math;

// draw on canvas drawing context
drawOnCanvas2D('#playground', (ctx) => {

    const rainbowStops = [
        [0, 'red'], [0.2, 'orange'], [0.4, 'yellow'], [0.6, 'green'], [0.7, 'cyan'],
        [0.8, 'purple'], [0.9, 'pink'], [1.0, 'red'],
    ];

    // linear gradient;
    ctx.fillStyle = ctx.gradient('linear', [10,10,10,190], rainbowStops);

    ctx.fillRect(10, 10, 10, 180);
    ctx.fillRect(30, 20, 40, 50);
    ctx.fillRect(30, 80, 40, 30);
    ctx.fillRect(30, 120, 40, 30);

    // radial gradient
    ctx.fillStyle = ctx.gradient('radial', [200,100,50, 200,100,100], [
        [0.0, 'transparent'], 
        [0.5, 'hsl(60 90% 50%)'], 
        [0.7, 'hsl(40 90% 50%)'], 
        [1.0, 'transparent'],
    ]);;
    
    ctx.beginPath();
    ctx.arc(200, 100, 100, 0, 2 * pi);
    ctx.fill();
    ctx.stroke();

    // conic gradient
    ctx.fillStyle = ctx.gradient('conic', [-pi/2, 200, 100], rainbowStops);

    ctx.beginPath();
    ctx.arc(200, 100, 50, 0, 2 * pi);
    ctx.fill();
});
```
{% endtab %}

{% tab title="📘 手冊" %}
* [CanvasRenderingContext2D](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D) ⟩&#x20;
  * [.createLinearGradient()](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient), [.createRadialGradient()](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createRadialGradient), [.createConicGradient()](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createConicGradient)
* [CanvasGradient](https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient) ⟩ [.addColorStop()](https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient/addColorStop) - define gradient colors
{% endtab %}
{% endtabs %}
