HTML and CSS Reference
In-Depth Information
myRectangle.fillRect(10,10,650,650);
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
(0,0,0,650);
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.
<html>
<head>
<title>Linear Gradient</title>
<script type=”application/x-javascript”>
function draw() {
var myRectangle = document.getElementById
('myCanvas').getContext('2d');
var verticalGradient = myRectangle.
createLinearGradient(0,0,0,650);
verticalGradient.addColorStop(0, 'red');
verticalGradient.addColorStop(0.5, 'yellow');
myRectangle.fillStyle = verticalGradient;
myRectangle.fillRect(10,10,650,650);
}
</script>
</head>
<body onload=”draw();”>
<canvas id=”myCanvas” width=”800”
height=”800”></canvas>
</body>
</html>
Search WWH ::




Custom Search