首页 > 解决方案 > 在 d3 中动态附加形状

问题描述

我正在尝试append根据datum. 我的对象是这样的:

const boom = [
  {
    shape: 'rect',
    color: 'red',
    width: 50,
    height: 50,
    x: 50,
    y: 100
  }
]

我的代码是这样的:

const stage = d3.select('stageContainer')
    .append('svg')
    .attr('width', 100)
    .attr('height', 100)
    .style('border-width', '2')
    .style('border-color', 'red')
    .style('border-style', 'solid')

stage.selectAll('.group01')
      .data(boom)
      .enter()
      .append(d => document.createElement(d.shape))
      .attr('fill', d => d.color)
      .attr('width', d => d.width)
      .attr('height', d => d.height)
      .attr('x', d => d.x)
      .attr('y', d => d.y)

我可以看到它正在添加到 DOM,但实际上并没有呈现。

标签: d3.jssvg

解决方案


要创建 SVG 元素,您必须使用document.createElementNS

.append(d => document.createElementNS('http://www.w3.org/2000/svg', d.shape))

或者,您可以使用以下中的内置命名空间d3.namespaces

.append(d => document.createElementNS(d3.namespaces.svg, d.shape))

这是您进行更改的代码:

const boom = [{
  shape: 'rect',
  color: 'blue',
  width: 50,
  height: 50,
  x: 40,
  y: 10
}];

const stage = d3.select('body')
  .append('svg')
  .attr('width', 100)
  .attr('height', 100)
  .style('border-width', '2')
  .style('border-color', 'red')
  .style('border-style', 'solid')

stage.selectAll('.group01')
  .data(boom)
  .enter()
  .append(d => document.createElementNS(d3.namespaces.svg, d.shape))
  .attr('fill', d => d.color)
  .attr('width', d => d.width)
  .attr('height', d => d.height)
  .attr('x', d => d.x)
  .attr('y', d => d.y)
<script src="https://d3js.org/d3.v5.min.js"></script>

PS:更改该矩形的位置,否则它将落在 SVG 之外。


推荐阅读