Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create "svg" object without appending it?

Consider the following code:

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

I would like to refactor this code so that it reads more like this:

var svg = makesvg(w, h); d3.select("#somediv").append(svg); 

Note that, in contrast to the situation shown in the first version, in this second version append does not create the "svg" object; it only appends it to d3.select("#somediv").

The problem is how to implement the function makesvg. This in turn reduces to the problem: how to instantiate an "svg" object without using append to do this, since one could then do something like:

function makesvg(width, height) {   return _makesvg().attr("width", w).attr("height", h); } 

So my question boils down to what is the generic equivalent of the hypothetical _makesvg() factory mentioned above?

like image 740
kjo Avatar asked Aug 27 '13 00:08

kjo


People also ask

How to create SVG using D3?

To create SVG using D3. js, let us follow the steps given below. Step 1 − Create a container to hold the SVG image as given below. Step 2 − Select the SVG container using the select() method and inject the SVG element using the append() method.

Can we group SVG elements in d3js?

The <g> SVG element is a container used to group other SVG elements. Transformations applied to the <g> element are performed on its child elements, and its attributes are inherited by its children. We can create a group element with D3. js by appending a g element using any selection.

What is SVG append G?

It appends a 'g' element to the SVG. g element is used to group SVG shapes together, so no it's not d3 specific.

What is use of DOM and SVG in D3?

SVG is text-based, and it is an image format that is vector-based. SVG is the same as the HTML structure. It can be illustrated as the DOM (Document Object Model). The properties of SVG can be described as attributes.


1 Answers

You can use the following:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); 

Note the use of createElementNS. This is required because svg elements are not in the same XHTML namespace as most HTML elements.

This code creates a new svg element, as you would regardless of using D3 or not, and then creates a selection over that single element.

This can be made marginally more succinct but clearer and less error prone as:

var svg = document.createElementNS(d3.ns.prefix.svg, 'svg'); 
like image 113
Drew Noakes Avatar answered Oct 13 '22 23:10

Drew Noakes