CanvasGradient object
[This documentation is preliminary and is subject to change.]
Specifies an object that represents a color gradient on a CanvasRenderingContext2D 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.
Examples
The following code example creates a gradient.
<!DOCTYPE html>
<head>
<script type="text/javascript">
function draw()
{
var canvas = document.getElementById("MyCanvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
//create a gradient object from the canvas context
gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
// Add the colors with fixed stops at 1/4 of the width.
gradient.addColorStop("0","magenta");
gradient.addColorStop(".25","blue");
gradient.addColorStop(".50","green");
gradient.addColorStop(".75","yellow");
gradient.addColorStop("1.0","red");
// Use the gradient.
ctx.fillStyle = gradient;
ctx.fillRect (0,0,300,250);
ctx.fillRect(250,300,600,500);
}
}
</script>
</head>
<body>
<canvas id="MyCanvas" width="600" height="500" border="1"> </canvas>
<button onclick="draw()">Click me</button>
</body>
</html>
See also
- Reference
- createRadialGradient
- createLinearGradient
Build date: 2/14/2012

