๐Ÿ’พctx.gradient()

browser โŸฉ canvas โŸฉ gradient โŸฉ 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