💾ctx.gradient()

browsercanvasgradient ⟩ ctx.gradient()

💾 replit: canvas gradients

// ⭐ 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;
};

Last updated