Lesson 25
Canvas: Part II
In the previous lesson, you learned how to use the Canvas API to create simple two-dimensional bitmaps. This lesson will consolidate your knowledge from the previous lesson, and also look at some of the more advanced canvas features, such as animation.
Linear Gradients
In the previous lesson, all lines and shapes used block colors. Linear gradients allow you to create colors that start with a specific color and end with another color, and gradually transform from one color to the other over the area of the feature being colored.
In order to create a linear gradient, you first need to use the createLinearGradient
method, and specify the x and y coordinates for an imaginary line through which the color should be transformed. For example:
var gradient = context.createLinearGradient(50,0,350,0);
In this case, the gradient runs horizontally from the x-coordinate of 50 to the x-coordinate of 350. This is not coloring any feature; it is just creating a line through which features can be colored with a linear gradient.
Next, you need to specify the color at specific points along the line using the addStopColor
method. Usually, specifying the starting and ending color is sufficient, but you can specify the color for as many points along the line as you need. The following specifies the color for the start and end of the line:
gradient.addColorStop(0.0, "black");
gradient.addColorStop(1.0, "white");
The first parameter to addStopColor
represents the position ...
Get HTML5, JavaScript, and jQuery 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.