1

I'm wondering about a canvas-based implementation of Mike Bostock's SVG-based stroke-dash interpolation method. I gather one of canvas's differences to SVG is that since "once a shape is drawn, there is no way to modify it or style it" (from Roger Veciana i Rovira). So is this method something that in principle canvas can support, or will I be wasting my time?

If it is possible, any pointers would be greatly appreciated.

Thanks in advance. enter image description here

geotheory
  • 22,624
  • 29
  • 119
  • 196

1 Answers1

2

The short answer is yes, you can do this, but you probably wouldn't want to. The slightly longer answer is that it's much more complicated than in SVG -- you can't use the same techniques, because that relies on things that aren't present in canvas.

When going away from SVG, you lose everything D3 offers for it (and that's offered by SVG itself), such as line generators, interpolation and stroke-dasharray attributes. I've made a simplistic (and not very D3) example of animating a path here. You can see the basic technique, but for anything more sophisticated (e.g. animated drawing of individual paths) you would have to create your own interpolator that gives you the sequence of points along the path and draw those explicitly one-by-one onto the canvas. And that's just for simple linear interpolations.

So to reproduce the above example in canvas, you would need to implement a function that interpolates the path with a cardinal spline between the points and allows you to get the position of each point along the line and then pass that to a setTimeout function that draws each point after a small delay to give you the illusion that the line is drawn smoothly. For the dashed line at the start, it would be similar except that you would have to get the dashes instead of the points.

You could probably reuse parts of the implementation of D3's SVG line generator for that, but it would still be quite some effort.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204