使用 d3.create 创建和附加分离的元素

IT技术 javascript d3.js svg
2021-02-13 12:43:53

假设我创建了一个像这样的简单图形:

<!doctype html>
<html lang="en">

<head>
  <script src="https://d3js.org/d3.v5.min.js"></script>
</head>

<body>
  <svg></svg>
  <script>
    const svg = d3.select('svg');
    const g = svg.append('g');

    g.append('g')
      .selectAll('g')
      .data([5, 10, 20, 40])
      .enter()
      .append('rect')
      .attr('fill', 'green')
      .attr('x', d => d)
      .attr('y', d => d)
      .attr('height', d => d)
      .attr('width', d => d);
  </script>
</body>

</html>

但不是仅仅附加到它,我想创建一个分离的<g>,然后可以随意附加(例如它可以从函数返回)。

d3 V5 有一个d3.create()函数可以创建一个分离的元素。

<!doctype html>
<html lang="en">

<head>
  <script src="https://d3js.org/d3.v5.min.js"></script>
</head>

<body>
  <svg></svg>
  <script>
    const svg = d3.select('svg');
    const g = svg.append('g');

    const detachedG = d3.create('g');
    detachedG.selectAll('g')
      .data([5, 10, 20, 40])
      .enter()
      .append('rect')
      .attr('fill', 'green')
      .attr('x', d => d)
      .attr('y', d => d)
      .attr('height', d => d)
      .attr('width', d => d);

    g.append(() => detachedG.node());
  </script>
</body>

</html>

但它不会出现在浏览器中,即使 DOM 看起来是一样的。

任何想法如何解决这一问题?

2个回答

只需命名它:

const detachedG = d3.create('svg:g');

这是具有该更改的代码:

解释

使用该append()方法附加 SVG 元素时,98.47% 的 D3 程序员不使用名称空间(来源:Fakedata Inc.)。因此,而不是:

selection.append("svg:rect")

我们通常只做:

selection.append("rect") 

那么,为什么这里需要一个命名空间?

在内部,d3.create使用以下方式d3.creator调用它document.documentElement

export default function(name) {
    return select(creator(name).call(document.documentElement));
}

这改变thisd3.creator方法。我们在创建 SVG 元素时通常不使用命名空间 using append(内部使用d3.creator),因为:

如果未指定命名空间,则命名空间将从父元素继承。

但是,由于使用了document.documentElementas this,在这种情况下命名空间变得必要。

@user2728841 在这种情况下,不需要命名空间,因为 div 是一个 HTML 元素。
2021-03-30 12:43:53
你会用什么命名空间来创建一个独立的 div ?d3.create("div:div") 可以吗?谢谢
2021-04-06 12:43:53

SVG 提供了不同的形状,如直线、矩形、圆形、椭圆等。因此,使用 SVG 设计可视化可为您提供更大的灵活性和功能。

    var width = 500;
    var height = 500;

    //Create SVG element
    var svg = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

    //Create line element inside SVG
    svg.append("line")
       .attr("x1", 100)
       .attr("x2", 500)
       .attr("y1", 50)
       .attr("y2", 50)
       .attr("stroke", "black")

了解更多

您确定要回答这个特定问题吗?鉴于问题的上下文,答案没有任何意义。
2021-04-03 12:43:53