Home :: Tutorials :: Simplifying a Polyline

Simplifying a Polyline - Introduction

SVG is gaining popularity as an application development environment. Naturally, given that SVG is a Graphics technology, many SVG developers eventually have a need or a desire to create an SVG-based drawing program.

Basic graphics elements like circles, lines, etc. are fairly simple to support, but sometimes hand-drawn input is desired. This tutorial discusses ways in which the point data produced by a hand-drawn curve can be reduced while maintaining the appearance of the original curve. The algorithm outlined includes the ability to specify a user-defined tolerance which the algorithm uses to control how faithfully it approximates the original curve. Higher tolerances reduce the point count but diminish the quality of the approximated curve. Whereas, lower tolerances result in curves that are truer to the original drawn by the user.

Sketching shapes with the mouse introduces unnecessary points due to the nature of how the points are sampled. Typically, the process goes like this. The user presses the mouse button to begin drawing. The user continues to hold the button down and drags the shape they desire to draw. The SVG viewer fires mousemove events at regular intervals allowing the drawing program to add new points to the shape being drawn. Then the user releases the mouse button ending the drawing process. This approach is fairly simple, but it introduces unneeded points in the final polyline.

The first problem occurs because mousemove events fire at somewhat regular intervals. If you leave your mouse in one position for a period of time, the curve will accumulate points at that position, one point for each mousemove event. It turns out that it is best to prevent duplicate points as the curve is being drawn. If your mousemove handler knows the previously drawn point, it can compare the current mouse position to that point. If the two match, then the handler can exit thereby preventing the duplicate point from being added to the polyline.

The second way we get unnecessary points is similar to the first, but occurs as we drag. If the user drags a perfectly straight line, then each mousemove event will add points to the line. We need only two points to draw a line, so all other points in that line are unnecessary. The solution to this case is the topic for the rest of this tutorial.