Typescript Math Toolkit Line Decorators

Decorator is one of my favorite design patterns.  I like how decoration can be applied at compile-time (see Typescript annotations such as @Component) and at run-time.  A great example of run-time decoration is line decorators.  Suppose you have a Canvas drawing application and wish to replace solid lines with a dashed pattern.  It is possible to grab something off the web that draws dashed-lines and switch out the code.  Then, what happens if someone wants to go back to solid lines?  It’s a constant mess of switching out or commenting/uncommenting blocks of code to implement the desired behavior.

With a line decorator, the actual line drawing is abstracted into an API.  Suppose we have a reference, g, to a graphic context.  Instead of g.moveTo() and g.lineTo(), the decorator implements moveTo(g, x, y) and lineTo(g, x, y).  The person implementing the drawing application should not really care how the lines are actually drawn.  Switching from solid to dashed lines is a simple matter of injecting a new line decorator.  The drawing code remains unchanged.

It is even possible to include dotted lines in such a strategy, although drawing dots implies drawing circles, which involves fills.  That has implications outside the decorator in terms of starting and terminating a ‘line’ segment.  This is illustrated in the following screen shot from the Javascript Math Toolkit.


Note the logic pertaining to beginning/ending strokes vs. fills if the decorator is ‘dotted’.  However, the actual line drawing code is *exactly* the same for solid, dashed, and dotted lines,

lineDecorator.moveTo(g, x0, y0);

lineDecorator.lineTo(g, x1, y1);

The Typescript Math toolkit will have the same three line decorators in its initial release.  The curveTo() method will not be supported.  I have already done the math for dashed and dotted quad. Beziers and implemented them in Actionscript.  It will be a matter of porting the AS code to Typescript and then testing.  That will be done in a dot release.

Here is a screen shot of current work with the dotted-line decorator in Typescript.


More to come!

Comments are closed.