💾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;
};
💾 replit: canvas gradients
⬆️ 需要: drawOnCanvas2D()
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();
});
CanvasGradient ⟩ .addColorStop() - define gradient colors
Last updated