javascript - 如何使用 json 文件中的数据修改现有 svg 对象的标签
问题描述
我有这个代码片段:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="d3.min.js"></script>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000" stroke="#000" stroke-linecap="round" stroke-linejoin="round" fill="none" fill-rule="evenodd">
<path d="M377.4528 264.0669q3.7795-113.3858 151.1811-113.3858m0 0q0 11.3386 0 11.3386 0 139.8425-41.5748 139.8425m3.7795 0q-37.7953 0-37.7953 0 56.6929 0 56.6929 113.3858-132.2835 0-132.2835-79.3701"/>
<path d="M377.4528 335.878q0 79.3701-132.2835 79.37-3.7795-113.3857 56.6929-113.3857-75.5905 0-75.5905-151.1812 151.1811 0 151.1811 113.3859"/>
<ellipse cx="377.4528" cy="284.8543" rx="3mm" ry="16.5mm"/>
</svg>
<script type="text/javascript">
d3.json("./data.json").then(function(data){
var svg = d3.select("body")
.selectAll("svg")
.... something here
})
</script>
</body>
我无法使用 data.json 文件中的值进行更新,例如cx
,cy
等...以及字符串rx
中包含的大多数值。path
有人可以帮助我吗?谢谢大家。
解决方案
在下面的示例中,我使用模拟 API 来模拟您的d3.json()
请求,然后为椭圆创建一个新rx
值ry
。我使用 timeout 只是为了演示目的,这样您就可以看到椭圆的变化——您不需要在代码中这样做。
因此,一旦有了新数据,您就可以使用选择,例如d3.select("svg ellipse")
,这样您就可以更新选择的属性。
如果您的新数据具有元素的新d
属性path
,那么您可以使用相同的方法,例如path.attr("d", newD)
. 如果您想更改路径定义中的数据点,这将取决于您传入的数据,最好作为一个单独的问题提出。
// mock api to make this snippet work
const url = "https://jsonplaceholder.typicode.com/todos/1";
// wait for 1.5s and apply new attributes to ellipse
setTimeout(function() {
// get the new data
d3.json(url).then(function(data) {
// mock up some data
data = [{rx: "5mm", ry: "20mm"}];
changeEllipse(data[0]);
});
}, 1500);
function changeEllipse(data) {
// select the ellipse with a selector
const ellipse = d3.select("svg ellipse");
// change attributes
ellipse
.attr("rx", data.rx)
.attr("ry", data.ry);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000" stroke="#000" stroke- linecap="round" stroke-linejoin="round" fill="none" fill-rule="evenodd">
<path d="M377.4528 264.0669q3.7795-113.3858 151.1811-113.3858m0 0q0 11.3386 0 11.3386 0 139.8425-41.5748 139.8425m3.7795 0q-37.7953 0-37.7953 0 56.6929 0 56.6929 113.3858-132.2835 0-132.2835-79.3701"/>
<path d="M377.4528 335.878q0 79.3701-132.2835 79.37-3.7795-113.3857 56.6929-113.3857-75.5905 0-75.5905-151.1812 151.1811 0 151.1811 113.3859"/>
<ellipse cx="377.4528" cy="284.8543" rx="3mm" ry="16.5mm"/>
</svg>
推荐阅读
- android - file.createFile 不起作用。安卓 10
- python - 如何加快python中的嵌套for循环?
- python - 在 Python 中处理大数(16 位)的对数和反对数操作
- python - 如何在 Colab 中显示 matplotlib 动画而不显示情节?
- android - 如何在 android os 的 Pepper 平板电脑上制作 Kiosk 模式?
- python - set_password() 方法正在保存纯文本
- kubernetes - 有没有办法在集群中首先部署 statefulset?
- javascript - jquery-单击按钮时验证特定元素
- mysql - mysql中的INTERSECT无法运行
- javascript - 在 JavaScript 中检查其中一些复选框后禁用剩余的复选框