javascript - 从字符串创建 svg 元素

标签 javascript d3.js svg

因为我想检查 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/

相关文章:

javascript - Nightmare Js 多次评估后评估超时

javascript - 如何从需要返回语句的 GraphQL 解析器中调用异步 node.js 函数?

javascript - 如何在 Controller 中加载指令?

javascript - 将 Base64 图像字符串转换回文件以发送到 Parse upload

json - 使用来自 API 的 JSON 数据的 D3 线图

javascript - d3.js 简单的 csv 树形图两列

javascript - 如何在 StackedAreChart 中使用 nvd3.js 制作 xAxis 每小时刻度(如 0,1,2,...,23)?

javascript - 第 39 行第 26 列错误 : Namespace prefix xlink for href on script is not defined

javascript - 如何让瓶子看起来静止不动

javascript - 为什么我的表单发布函数会打开我的 .pl 文件而不是执行它?