You can add a gradient color in canvas by using the createLinearGradient()
or createRadialGradient()
methods to create a gradient object and then setting it as the fill style of the canvas context.
Here's a breakdown of how to achieve this:
Creating Gradients
Canvas provides two primary methods for creating gradients:
createLinearGradient(x0, y0, x1, y1)
: Creates a linear gradient between the points (x0, y0) and (x1, y1).createRadialGradient(x0, y0, r0, x1, y1, r1)
: Creates a radial gradient between two circles, where (x0, y0) and r0 represent the center and radius of the starting circle, and (x1, y1) and r1 represent the center and radius of the ending circle.
Steps to Add a Gradient Color
-
Get the Canvas Context: Obtain the 2D rendering context of the canvas element.
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d');
-
Create a Gradient Object: Use
createLinearGradient()
orcreateRadialGradient()
to create the gradient.-
Linear Gradient Example:
const gradient = ctx.createLinearGradient(0, 0, 200, 0); // Starts at (0,0), ends at (200,0) - horizontal gradient
-
Radial Gradient Example:
const gradient = ctx.createRadialGradient(100, 75, 25, 100, 75, 75); //Inner circle at (100,75) radius 25, outer circle at (100,75) radius 75
-
-
Add Color Stops: Use the
addColorStop(offset, color)
method to add colors to the gradient. Theoffset
is a value between 0 and 1, representing the position of the color within the gradient.gradient.addColorStop(0, 'red'); // Start with red gradient.addColorStop(0.5, 'white'); // Transition to white at the middle gradient.addColorStop(1, 'green'); // End with green
-
Set the Fill Style: Assign the gradient object to the
fillStyle
property of the canvas context.ctx.fillStyle = gradient;
-
Draw the Shape: Use canvas drawing methods (e.g.,
fillRect()
,arc()
) to draw the shape with the gradient fill.ctx.fillRect(0, 0, 200, 150); // Draw a rectangle filled with the gradient
Complete Example (Linear Gradient)
<!DOCTYPE html>
<html>
<head>
<title>Canvas Gradient Example</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.
</canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Create a linear gradient
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(0.5, 'white');
gradient.addColorStop(1, 'green');
// Set the fill style and draw a rectangle
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 150);
</script>
</body>
</html>
This will display a rectangle with a horizontal gradient that transitions from red to white to green.