[英]How to modify tags of an already existing svg object with data from json file
我有这个代码片段:
<!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")
,这样您就可以更新选择的属性。
如果您的新数据具有path
元素的新d
属性,那么您可以使用相同的方法,例如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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.