繁体   English   中英

D3 - 如何通过 function 将 SVG 放入 DIV?

[英]D3 - How can I put an SVG into a DIV via a function?

为了重用代码,我想将我的 SVG 放入 function 并根据需要调用它。 一旦我 select 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;
   }

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 function 传递给您要将其添加到的 div 选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM