如何创建“svg"对象而不附加它? [英] How to create "svg" object without appending it?

查看:19
本文介绍了如何创建“svg"对象而不附加它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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

请注意,与第一个版本中显示的情况相反,在第二个版本中append 不会创建svg"对象;它只将它附加到 d3.select("#somediv").

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").

问题是如何实现makesvg函数.这反过来又变成了一个问题:如何在不使用 append 的情况下实例化一个svg"对象,因为然后可以做类似的事情:

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

所以我的问题归结为上面提到的假设的 _makesvg() 工厂的通用等价物是什么?

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

推荐答案

您可以使用以下内容:

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

注意createElementNS 的使用.这是必需的,因为 svg 元素与大多数 HTML 元素不在同一个 XHTML 命名空间中.

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

此代码创建一个新的 svg 元素,无论是否使用 D3,您都会这样做,然后在该单个元素上创建一个选择.

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

这篇关于如何创建“svg"对象而不附加它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆