Sidebp
Sidebp

Reputation: 780

Dotted line bugs

I have adopted and adapted an HTML5 canvas extension which draws dotted lines, but it has a couple of problems as shown in http://jsfiddle.net/VxCYL/2/

Example 1: How can I avoid the "bunching" up of dots where the distance between two points is very small (see the first corner at 30,50 going to 32,50). I guess I need to check the distance from the last point when determining whether to draw or move to the next point? The output looks clumsy when I have lots of points.

Example 2: Where the from.x is less than the to.x or the from.y is less than the to.y i.e. drawing backwards the moveTo does not behave as I would expect i.e. in the example shown the lines should still be joined up.

Thanks.

Upvotes: 1

Views: 176

Answers (3)

Sidebp
Sidebp

Reputation: 780

The last issue has now been resolved. The fix was to cater for Infinity or -Infinity when calculating the slope:

var slope = (dy / dx); slope = slope == Infinity || slope == -Infinity ? dy : slope;

Upvotes: 0

Sidebp
Sidebp

Reputation: 780

Thanks, you're a gent. Remarkably, I tried something similar but in my ignorance set the dx<0 to dx<1.

There is one other problem which is shown in this Fiddle:

http://jsfiddle.net/VxCYL/5/

If the x or the Y are in-line then nothing gets rendered.

Upvotes: 0

Phrogz
Phrogz

Reputation: 303530

The first problem is not easily fixed in the library as it stands. It requires a wrapper method that takes an array of points so that it can accumulate and keep track of the current dot/dash state when 'rounding a corner'. (Time permitting I will write a method that does this; if I do so I will edit this answer and add a notification comment.)

You cannot handle this with the current current code by changing your dashArray.

For example, with a nominal dashArray of [2,9] the pattern repeats every 11px. If your first line is 115px, it means that you will have drawn 10 copies of the pattern, 2px of dot and 3px of dash. You want your next line thus to start with a 6px offset before drawing the next dot. You would need a dashArray of [0,6,2,9,2,9,2,9,2,9,2,9,...] until you had covered the length of your next line. :/


The second example is clearly a bug in the code. Here's a slightly simpler demo showing it:

Broken: http://jsfiddle.net/VxCYL/3/

To fix it, we need to ensure that xStep is negative when dx is negative. We add this one line in:

if (dx<0) xStep = -xStep;

Fixed: http://jsfiddle.net/VxCYL/4/

Upvotes: 2

Related Questions