D3 在一次调用中绘制不同的 SVG 形状,没有可见性

D3 draw different SVG shapes in one call, no visiblity

我有一个对象来存储 svg 形状的信息。它具有以下结构:

  Shapes = {
        id: <Shape ID>,
        objType: <Tag Name of Shape e.g ellipse or line>,
        Coordinates: < Object Containing relevant data for drawing >,
        Style:  <Object Containing relevant data for styling>,
 }

Examples for Coordinates and Style could be:
 Shapes.Coordinates = {
     x1: 10, // for Lines
     y1: 10,
     x2: 100,
     y2: 100,
 }

 Shapes.Coordinates = {
     cx: 10 ,// for Circles
     cy: 10,
     r: 10,
 }

 Shapes.Style = {
    fill: "black",
    stroke: "red",
    "stroke-width": 10
 }

现在我想要一个 D3 调用来利用给定的数据,根据对象数据绘制不同的形状。到目前为止,我最好的想法是以下代码:

首先,我创建了每个没有属性的形状,只有 ID 和事件。

    let objectsRender = svg.selectAll("line") 
                       .data(data)
                       .enter()
                       .append(function(d) {
                         return document.createElement(d.objType);
                       })
                       .attr("id", function(d){ return prefix +d._id;})
                       .attr("class", "no-attr")
                       .on("click",(d)=>{this.modeClick(d);});

然后我在第二次调用中添加了属性,通过使用 for 循环找到正确的 id,我认为这不是一个好的解决方案。通过查找带有 class no-attr

的任何标签,我可以找到 "empty" svg 标签
let objectsAttributes=  svg.selectAll(".no-attr").each(function(){
    let id= d3.select(this).attr("id");
    let d = null;
    d = data[0];

    for(i = 0;i < props.data.length; i++){
      if(id == prefix +props.data[i]._id){
        d = props.data[i];
        break;
      }
    }

    if( d !== null){
    d3.select(this)
      .attr(d.coordinates)
      .attr(d.style)
      .attr("class", null);
    }

到目前为止,这个临时解决方案创建了所有具有相关属性的形状。 但是形状不可见,跟append调用有关

                       .append(function(d) {
                         return document.createElement(d.objType);
                       })

谁能提出更好的解决方案或告诉我,为什么我的 svg 在我的浏览器上不可见 windows,但通过开发工具可见?

无法使用 document.createElement 创建 SVG 元素,该方法只能创建 html 个元素。

SVG 元素必须通过 document.createElementNS('http://www.w3.org/2000/svg', ) 在 SVG 命名空间中创建,所以我想在你的情况下你会想要

.append(function(d) {
      return document.createElementNS('http://www.w3.org/2000/svg', d.objType);
})

浏览器工具显示您已经创建了 html 个与您真正想要的 SVG 元素同名的元素,但由于它们是 html 个元素,所以它们没有功能。