CanvasGradient object
Specifies an object that represents a color gradient fillStyle on a CanvasRenderingContext2D object.
![]() ![]() |
Members
The CanvasGradient object has these types of members:
Methods
The CanvasGradient object has these methods.
| Method | Description |
|---|---|
| addColorStop |
Adds the specified colors and the position in a CanvasGradient object. |
Standards information
- HTML Canvas 2D Context, Section 1
Remarks
You can create a linear or radial CanvasGradient object by using the createLinearGradient or createRadialGradient method. A CanvasGradient object must have at least one color stop or the gradient is not visible.
Note If you are developing on an intranet and have rendering issues for HTML5, you can add a "meta http-equiv-'X-UA-Compatible' content= " meta command, followed by "IE=edge" to the <head> block of a webpage to force Windows Internet Explorer to use the latest standards. Remove this meta tag when you deploy the page on a server. For more information about document compatibility, see Defining Document Compatibility.
Examples
The following code example creates a gradient made up of 5 sections of the rainbow. When you click the button, it rotates the colors by shifting the first color in the array to the end of the array. See example live online.
<!DOCTYPE html> <html> <head> <title>Canvas gradient test</title> </head> <body> <h1>Canvas gradient test</h1> <button id="mybutton">Change colors</button> <p> <canvas id="MyCanvas" width="600" height="500"> This browser or document mode doesn't support canvas</canvas> </p> <script> var canvas = document.getElementById("MyCanvas"); if (canvas.getContext) { // check for support var ctx = canvas.getContext("2d"); var gradArray = ["red","purple","blue","green","yellow","orange"]; var gradient; var temp; doGradient(); // get an initial color set on the screen function doGradient() { //create a gradient object from the canvas context gradient = ctx.createLinearGradient(0, 0, canvas.width, 0); // Add the colors with fixed stops at 1/5 of the width. gradient.addColorStop("0", gradArray[0]); gradient.addColorStop(".20", gradArray[1]); gradient.addColorStop(".40", gradArray[2]); gradient.addColorStop(".60", gradArray[3]); gradient.addColorStop(".80", gradArray[4]); gradient.addColorStop("1.0", gradArray[5]); // Use the gradient. ctx.fillStyle = gradient; ctx.fillRect(0, 0, 300, 250); ctx.fillRect(250, 300, 600, 500); } } document.getElementById("mybutton").addEventListener("click", animate, false); function animate() { // rotate the colors by shifting off the bottom of the array, // and pushing it to the top temp = gradArray.shift(); gradArray.push(temp); doGradient(); // redisplay } </script> </body> </html>
See also
- Reference
- createRadialGradient
- createLinearGradient
Show:

