Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...