Canvas
- Canvas Introduction
- Canvas Draw Rectangles
- Canvas Draw Lines
- Canvas Draw Bezier
- Canvas Draw Quadratic
- Canvas Draw Arc
- Canvas Draw Paths
- Canvas Manipulating Images
- Canvas Linear Gradients
- Canvas Radial Gradients
- Canvas Text
- Canvas Pattern
- Canvas Shadow
- Canvas States
- Canvas Translate
- Canvas Rotate
- Canvas Scale
- Canvas Transform
- Canvas Composition
Canvas Radial Gradients
Photo Credit to CodeToFun
🙋 Introduction
Canvas radial gradients provide a powerful way to create smooth, multi-color transitions within circular areas on an HTML5 canvas. They are particularly useful for creating natural lighting effects, backgrounds, and other visually appealing graphics.
In this guide, we'll explore the syntax, attributes, and practical examples of using radial gradients in the HTML5 canvas.
💡 Syntax
Creating a radial gradient in an HTML5 canvas involves using the createRadialGradient method, which generates a gradient object that can be applied to shapes and paths. The basic syntax for creating a radial gradient is:
let gradient = ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);
🧰 Attributes
- x0, y0: Coordinates of the starting circle's center.
- r0: Radius of the starting circle.
- x1, y1: Coordinates of the ending circle's center.
- r1: Radius of the ending circle.
📄 Example
Let's create a simple canvas with a radial gradient:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Radial Gradient Example</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
let canvas = document.getElementById('myCanvas');
let ctx = canvas.getContext('2d');
// Create a radial gradient
let gradient = ctx.createRadialGradient(200, 200, 0, 200, 200, 200);
// Add color stops
gradient.addColorStop(0, 'red');
gradient.addColorStop(0.5, 'yellow');
gradient.addColorStop(1, 'green');
// Use the gradient to fill a rectangle
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 400, 400);
</script>
</body>
</html>
🧠 How it works?
In this example, we've created a radial gradient that transitions from red at the center to yellow at the midpoint and green at the outer edge. This gradient is then used to fill the entire canvas.
🎉 Conclusion
Radial gradients in the HTML5 canvas offer a rich and versatile way to enhance your web graphics.
By mastering the syntax and understanding how to control gradient attributes, you can create dynamic and visually stunning effects that enhance the user experience on your web pages. Experiment with different color stops and radii to discover the full potential of canvas radial gradients.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (Canvas Radial Gradients), please comment here. I will help you immediately.