因为我想检查 d3js 是否可以满足我的愿望,我需要知道如何从给定的字符串创建一个 svg 元素。
我的元素存储在数据库中。 它们是字符串,遵循 svg 规则,如下所示:
<desc>
<Insert x='21' y='21'/>
<Pins>
<Pin Id='1' x='21' y='1' direction='up' />
<Pin Id='2' x='21' y='41' direction='down' />
</Pins>
<Properties>
<Property Id='20010' x='0' y='21' angle='0'></Property>
</Properties>
</desc>
<circle class='CDC300' cx='21' cy='21' r='20' fill='none'></circle>
<polyline class='CDC300' points='1 21 21 1 41 21' fill='none' />
<text id='20010' class='CDC400' text-anchor='end' x='-2' y='25' >#{BMK}</text>
在用这个字符串创建一个 svg 元素之前,我想添加一个 g 标签(组),我需要添加 transform='translate( some value of database )' . 好的,最后一件事我希望我可以用 d3 做得更好。
那么我该如何开始呢? 我找到了大量的示例和教程,但没有一个将 svg 元素存储在数据库中,只有一些坐标或非常简单的数据来放置和设置 svg 的样式。
最佳答案
对于现代浏览器* 你可以使用html()
将整个字符串附加到您的 <g>
元素。
这是一个基本的演示。我们首先创建 <g>
元素,然后将它翻译成你想要的值,最后我们使用数据库中的字符串:
const string = `<desc>
<Insert x='21' y='21'></Insert>
<Pins>
<Pin Id='1' x='21' y='1' direction='up'/>
<Pin Id='2' x='21' y='41' direction='down'/>
</Pins>
<Properties>
<Property Id='20010' x='0' y='21' angle='0'></Property>
</Properties>
</desc>
<circle class='CDC300' cx='21' cy='21' r='20' fill='blue'></circle>
<polyline class='CDC300' points='1 21 21 1 41 21' fill='red' />
<text id='20010' class='CDC400' text-anchor='end' x='-2' y='25' >#{BMK}</text>`;
const svg = d3.select("svg");
const g = svg.append("g").attr("transform", "translate(100,50)");
g.html(string);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>
此外,要使其正常工作,您必须正确关闭元素,例如:
<Insert x='21' y='21'></Insert>
* 因为 html
使用 innerHTML
在内部,这不适用于旧浏览器中的 SVG 元素。
关于javascript - 从字符串创建 svg 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57907604/