【问题标题】:D3 - How can I put an SVG into a DIV via a function?D3 - 如何通过函数将 SVG 放入 DIV?
【发布时间】:2022-03-12 00:52:52
【问题描述】:

为了重用代码,我想将我的 SVG 放入一个函数并根据需要调用它。一旦我选择了 DIV,在其中呈现 SVG 的适当构造是什么?

...

if (intLocations.includes(comm.location)) {
  const intActivities = d3.select(\'div#intActivities\')
  intActivities.append(Pill(comm))
} else {
  const extActivities = d3.select(\'div#extActivities\')
  actActivities.append(Pill(comm))
}

...

function Pill(comm) {
   const svgNode = d3.create(\'svg\')
   svgNode
       .attr(\'width\', 100)
       .attr(\'height\', 100)
       .append(\'g\')
       // More code to draw the figure using comm data.
   return svgNode;
   }

    标签: javascript d3.js observablehq


    【解决方案1】:

    intActivities.append(() => Pill(comm).node()) 应该可以解决问题。这是一个例子:

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="UTF-8">
      <script src="https://d3js.org/d3.v7.js"></script>
    </head>
    
    <body>
      <div id="my-div"></div>
    
      <script>
        d3.select('#my-div').append(() => square().node());
    
        function square() {
          const svg = d3.create('svg')
              .attr('width', 100)
              .attr('height', 100);
    
          svg.append('rect')
              .attr('width', 100)
              .attr('height', 100)
              .attr('fill', 'navy');
    
          return svg;
        }
      </script>
    </body>
    
    </html>

    或者,您可以将您的 Pill 函数传递给您想要添加的 div 选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 2016-01-07
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      相关资源
      最近更新 更多