Can D3 print to an image buffer?

I just finished a random walk simulation based on Mike Bostock’s Dampened Random Walk notebook. The way he does it is to create a d3 line, then tween a creation and exit animation, and last .remove() the line. It works great, but it slows down if you add a lot of lines.

I think it would be really cool to render each SVG line to an image buffer that is not cleared each frame, so you could print as many lines as you want. Then each frame, apply a convolution blur that
blurs the color and fades out to white over time.

Does anyone know how to do this? Should I look into learning canvas, WebGL, or something else?

I think you’re looking for canvas APIs.

Recently I realized the line generators in d3 can be used to draw directly in canvas. So, you could draw multiple lines in canvas without clearing it in between. Blurring between each render would be trickier though?

1 Like

No, you can just draw the canvas onto itself. Untested example code:

ctx.save();
ctx.filter = 'blur(1)';
ctx.drawImage(ctx.canvas, 0, 0);
ctx.restore();

This notebook might also help to serve as an example: Hexagon 3 / Fabian Iwand / Observable


Slow fade effects in canvas are somewhat tricky due to premultiplied alpha, and you’ll end up with a greyish blur if you set your opacity (or globalAlpha) too low. In the past I worked around this by using a noise mask: Squaring the circle, part 2 - bl.ocks.org

2 Likes