๐พctx.gradient()
Last updated
Last updated
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;
};
โฌ๏ธ ้่ฆ๏ผ 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
replit: canvas gradients