I’ve used a html canvas to create this line:
I want the loops in the line filled, so that it looks like this:
However when I fill this it simply turns into:
I did try using paths, it was the exact same result, just with a line connecting the start to finish.
Abstraction of code:
var canvas = $("canvas"), ctx=canvas.getContext("2d"); ctx.moveto(0,0); // code to stroke path of mouse cursor;
How can I get my desired result and fill in just the enclosed shapes in the line?
The problem is as Brett points out that
fill() will implicitly close the path. There is nothing we can do about this using the API so we need to use a manual approach to fill the loops as separate closed paths.
This algorithm does the following (have not checked for cases where these loops might overlap, but it should get you started). It can also be rewritten to do this in real-time while moving the mouse.
- We can iterate over all segments in the path. Compare each segment to all the others, but from current + two as the end-point of current segment would otherwise self-intersect with start point of next segment.
- If an intersection is found:
- Build a path from the intersection point then add points using the segments between first and last intersecting line
<canvas id=c width=500 height=500></canvas>