HTML and CSS Reference
In-Depth Information
Figure 2-27. A vertical gradient example
The only difference between
Example 2-18
and
Example 2-17
is the line creating the
linear gradient.
The horizontal version (
Example 2-17
):
var gr = context.createLinearGradient(0, 0, 100, 0);
The new vertical version (
Example 2-18
):
var gr = context.createLinearGradient(0, 0, 0, 100);
All of the same rules for strokes on horizontal gradients apply to vertical ones.
Exam-
ple 2-19
takes the shape from
Example 2-18
, stroking it with the gradient instead of
filling it, producing the outline shown in
Figure 2-28
.
Example 2-19. A vertical gradient stroke
function drawScreen() {
var gr = context.createLinearGradient(0, 0, 0, 100);
// Add the color stops.
gr.addColorStop(0,'rgb(255,0,0)');
gr.addColorStop(.5,'rgb(0,255,0)');
gr.addColorStop(1,'rgb(255,0,0)');
// Use the gradient for the fillStyle.
context.strokeStyle = gr;
context.beginPath();
context.moveTo(0,0);
context.lineTo(50,0);
context.lineTo(100,50);
context.lineTo(50,100);
context.lineTo(0,100);
context.lineTo(0,0);
context.stroke();
context.closePath();
}
Diagonal gradients.
You can easily create a diagonal gradient by varying both the second
x
and second
y
parameters of the
createLinearGradient()
function:
var gr= context.createLinearGradient(0, 0, 100, 100);