How to create “svg” object without appending it?

后端 未结 6 566
天涯浪人
天涯浪人 2020-12-16 09:24

Consider the following code:

var svg = d3.select(\'#somediv\').append(\"svg\").attr(\"width\", w).attr(\"height\", h);

I would like to refa

6条回答
  •  庸人自扰
    2020-12-16 10:10

    D3 author Mike Bostock suggests another (simpler) approach in his comment on an old D3 Github "issue" asking about this very topic:

    Another strategy you could consider is to remove the element from the DOM immediately after creating it:

    var svg = d3.select("body").append("svg")
        .remove()
        .attr("width", w)
        .attr("height", w);
    
    svg.append("circle")
        .attr("r", 200);
    
    document.body.appendChild(svg.node());
    

    This approach does indeed append the element on creation, but .removes it immediately prior to manipulation and creation of child elements, so there should be no browser repaint. While technically contrary to the original question, this is probably the most idiomatic way to meet the requirement.

提交回复
热议问题