【问题标题】:Create svg element from string从字符串创建 svg 元素
【发布时间】:2020-01-14 09:13:08
【问题描述】:

我想检查 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-tag(组),我需要添加 transform='translate(some value of database)' . 好的,我希望我能用 d3 做得更好的最后一件事。

那么我该如何开始呢? 我找到了大量示例和教程,但没有一个将 svg 元素存储在数据库中,只有一些坐标或非常简单的数据来放置和设置 svg 样式。

【问题讨论】:

    标签: javascript d3.js svg


    【解决方案1】:

    对于现代浏览器*,您可以使用html() 将整个字符串附加到您的&lt;g&gt; 元素中。

    这是一个基本的演示。我们首先创建 &lt;g&gt; 元素,然后将其转换为您想要的值,最后我们使用数据库中的字符串:

    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 元素。

    【讨论】:

    • 啊好吧,这很简单。然后 g 是我可以使用的对象......到目前为止谢谢。
    • Gerardo,你写道我必须像 这样关闭元素 对于 svg 元素,像这样关闭它们还不够吗? 还是 d3 有这个问题?
    • @Telefisch 没关系:stackoverflow.com/a/24301479/5768908。但是,在上面的演示中,有一个区别。不过,这个问题与 D3 无关。
    • 你好,我确实像上面假设的那样,它工作正常,但是 g-tag 会干扰一些动作,比如移动或操纵线条等简单图形......所以有没有办法创建 svg 元素没有 g-tag,来自上面的给定字符串?
    • @Telefisch 请不要在 cmets 部分提问。将其作为新问题发布,并附上相关详细信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 2011-03-28
    • 2016-06-17
    相关资源
    最近更新 更多