HTML and CSS Reference
In-Depth Information
for (i = 1; i < numPoints - 2; i++) {
ctrlPoint.x = (points[i].x + points[i+1].x) / 2;
ctrlPoint.y = (points[i].y + points[i+1].y) / 2;
context.quadraticCurveTo(points[i].x, points[i].y, ctrlPoint.x, ctrlPoint.y);
}
//curve through the last two points
context.quadraticCurveTo(points[i].x, points[i].y, points[i+1].x, points[i+1].y);
context.stroke();
};
</script>
</body>
</html>
In the new code, the second for loop starts at 1 and ends at numPoints - 2 . This prevents it from
processing the first and last pairs of points. It creates a new x, y control point, which is the average of the
next two points in the array. Then, it draws a curve through the next array point to the new average point.
When the loop ends, the index, i continues pointing to the second-to-last element; thus, you can draw a
curve through that to the last point.
This time, you come up with a nice smooth shape—rather than those spikes—as shown in Figure 4-3. You
are not limited to an odd number of original points anymore. As long as you start with at least three points,
you'll be fine.
As a variation on this theme, the following code, document 06-multi-curve-3.html , creates a closed
curve using the same technique. It computes an initial midpoint, which is the average of the first and last
points, and moves to that. Then it loops through all the rest, figuring midpoints for each one, finally drawing
its last curve back to the initial midpoint (see Figure 4-4).
Figure 4-3. Smooth multiple curves
 
Search WWH ::




Custom Search