The CanvasRenderingContext2D.createRadialGradient()
method of the Canvas 2D API creates a radial gradient using the size and coordinates of two circles.
This method returns a CanvasGradient
. To be applied to a shape, the gradient must first be assigned to the fillStyle
or strokeStyle
properties.
Note: Gradient coordinates are global, i.e., relative to the current coordinate space. When applied to a shape, the coordinates are NOT relative to the shape's coordinates.
createRadialGradient(x0, y0, r0, x1, y1, r1)
The createRadialGradient()
method is specified by six parameters, three defining the gradient's start circle, and three defining the end circle.
A radial CanvasGradient
initialized with the two specified circles.
This example initializes a radial gradient using the createRadialGradient()
method. Three color stops between the gradient's two circles are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle.
HTML
<canvas id="canvas" width="200" height="200"></canvas>
JavaScript
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const gradient = ctx.createRadialGradient(110, 90, 30, 100, 100, 70);
gradient.addColorStop(0, "pink");
gradient.addColorStop(0.9, "white");
gradient.addColorStop(1, "green");
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 160, 160);
Result