HTML and CSS Reference
In-Depth Information
The next step is to create a new variable that declares a new
gradient. The following line creates a new gradient that is named
verticalGradient. The name is arbitrary; what is not arbitrary is
the description of the gradient type that follows the name.
var verticalGradient = myRectangle.createLinearGradient
Here you are associating the gradient with the CANVAS object
myRectangle. At this point the gradient will not paint the image
that comes later—the code at this point merely associates the
gradient and the image. The property createLinearGradient dic-
tates where the gradient will paint an object. The values in the
parenthesis are the X and Y axes and height and width.
A gradient must have at least two colors. The following will
paint a gradient color that starts red and then transitions 50%
through the image to yellow.
verticalGradient.addColorStop(0, 'red');
verticalGradient.addColorStop(0.5, 'yellow');
The final step is to use the paintStyle property to paint the
gradient into the rectangle:
myRectangle.fillStyle = verticalGradient;
The whole CANVAS script looks as follows.
<title>Linear Gradient</title>
<script type=”application/x-javascript”>
function draw() {
var myRectangle = document.getElementById
var verticalGradient = myRectangle.
verticalGradient.addColorStop(0, 'red');
verticalGradient.addColorStop(0.5, 'yellow');
myRectangle.fillStyle = verticalGradient;
<body onload=”draw();”>
<canvas id=”myCanvas” width=”800”
Search WWH ::

Custom Search