Jake
Jake

Reputation: 2923

D3 force layout in Canvas: adding & updating nodes (& links)

I am handling a large dataset to render for D3 force-layout, but realised that the performance suffers a lot using SVG. Read that rendering in canvas is much better, so am trying to understand it now.

One of the functions I need to code for is the addition of new nodes & links in the existing graph (without a refresh), as well as new links. Is there any hack that can be done to do this? Since canvas doesn't have DOM structure like SVG for me to select and update...

Am referencing to this canvas force-layout create using d3v4. https://bl.ocks.org/mbostock/ad70335eeef6d167bc36fd3c04378048

Thanks!

Upvotes: 0

Views: 1338

Answers (1)

Ian
Ian

Reputation: 34549

There's a really good post that someone put together about using canvas called Working with D3.js and Canvas.

In short I'd recommend doing some data-binding into some dummy HTML, and using the results of this to render your output.

First create a fake DOM element that you can use

const fakeContainer = d3.select(document.createElement("custom"));

Now data-bind to it. Note, only create it the once, re-use it for re-renders.

const join = fakeContainer
        .selectAll("circle")
        .data(myData);

join.exit().remove();
join.enter().append("circle");

Then when it comes to rendering:

fakeContainer.each(function(d) {
    // Render a canvas circle
});

Upvotes: 1

Related Questions