d3.js - 在 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,但实际上并没有呈现。
解决方案
要创建 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 之外。
推荐阅读
- sql - 通过创建脚本的最后修改日期文件系统
- java - Java Swing:JTextArea 填充整个分配的空间
- c# - 如何使用串口转换器连接支付设备?(支付设备:Spire Payments SPc5)
- google-authentication - 赛普拉斯为 Google Authenticator 生成过时的代码
- ios - 如何在swiftUI中执行弹簧动画?
- webots - 锁定后如何连接连接器
- python - 在烧瓶应用程序中绘图以测量实时数据
- spring - 有没有办法在 TestExecutionListener 中获取对 Spring 应用程序上下文的引用?
- ruby-on-rails - 发出返回 xml 响应并解析 XML 字段的 http POST 请求
- javascript - 历史推送后 useState 重置