HTML canvas addColorStop() Method
-- Learning not just technology, but also dreams!
Table of Contents
Introduction
The addColorStop() method is used to define a color stop in a gradient. It specifies the position and color of a gradient stop.
Syntax
gradient.addColorStop(position, color)
- position: A number between 0.0 and 1.0 representing the position of the color stop along the gradient line (0.0 = start, 1.0 = end).
- color: A valid CSS color value (e.g., "red", "#FF0000", "rgb(255,0,0)").
Example
This example demonstrates how to create a linear gradient with two color stops using the addColorStop() method.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Create a linear gradient
const gradient = ctx.createLinearGradient(0, 0, 400, 0);
// Add color stops
gradient.addColorStop(0, 'blue');
gradient.addColorStop(1, 'red');
// Fill the rectangle with the gradient
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 400, 200);
Summary
The addColorStop() method is essential for creating smooth gradients in HTML Canvas. By setting multiple color stops at different positions, you can achieve visually appealing gradient effects.
YouTip