d3.js - 使用 D3 并通过附加 SVG 绘制两个圆圈
问题描述
我正在尝试使用 D3 并附加 SVG 来绘制两个圆圈。下面提供的代码没有产生预期的结果。它绘制了第一个绿色圆圈,但没有绘制下一个。请帮助我了解下面提供的代码有什么问题...
<!DOCTYPE HTML>
<html>
<head>
<title>Selection Method
</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
d3.select("body")
.append("svg")
.attr("width", 960)
.attr("height", 500)
.style('background', '#dff0d8')
.append("g")
.attr("transform", "translate(0,0)")
.append("circle")
.attr("cx", 20)
.attr("cy", 20)
.attr("r", 10)
.attr("fill", "green")
.append("circle")
.attr("cx", 70)
.attr("cy", 70)
.attr("r", 10)
.attr("fill", "black")
</script>
</body>
解决方案
您的代码尝试将第二个附加circle
到第一个circle
. 简单地“突出”代码不会改变范围。
这是一个微不足道的更改,可以得出您可能期望的结果:
d3.select("body")
.append("svg")
.attr("width", 960)
.attr("height", 500)
.style('background', '#dff0d8')
.append("g")
.attr("transform", "translate(0,0)")
.append("circle")
.attr("cx", 20)
.attr("cy", 20)
.attr("r", 10)
.attr("fill", "green")
d3.select('g') // <- Note the reselection of the existing 'g' element
.append("circle")
.attr("cx", 70)
.attr("cy", 70)
.attr("r", 10)
.attr("fill", "black")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
推荐阅读
- python - 如何正确编写带有条件 if 语句的 for 循环?
- angular - 为什么使用 OnPush 策略时即使输入没有改变,模板也会重新渲染?
- python - Python 3 损坏的文件写入 smb 共享(Python 2 有效)
- c - 如何扫描字符串直到出现特定单词
- javascript - 延迟评估 JavaScript 中的字符串文字
- java - Java - 覆盖实例字段
- javascript - 如何配置 webpack 以使用 'typings-for-css-modules' 加载器
- crash - 视频驱动程序崩溃并被重置
- python - 不知道如何解决这个背包问题
- r - 一个接一个地合并两个时间数据帧