D3 Does not render or paint DOM element

↘锁芯ラ 提交于 2021-01-28 01:05:00

问题


I'm trying to draw the SVG elements from an array of different shapes. I can see all shapes added to the document successfully but I cannot see them rendered on the screen. Interestingly, if I just try to edit the HTML element (without making any changes) from the browser's DOM explorer (in my case Chrome) the shapes get drawn as expected. Any suggestion of what's being done wrong here?

http://fiddle.jshell.net/1qd2kt9s/

Thanks

var my_data=[{"shape":"circle","attr":{"r":"50","cx":"60","cy":"60", "fill":"red"}  }
,{"shape":"rect","attr":{"width":"100","height":"100","x":"120","y":"10", "fill":"blue"}  }
            ];
var svg=d3.select('body')
    .append('svg')
        .attr("width",500)
        .attr("height",500);
var shapes=svg.selectAll('.shapes')
    .data(my_data);
shapes.enter()
    .append(function(d,i) {
        return document.createElement(d.shape);
    })
        .each(function(d,i){
           d3.select(this).attr(d.attr);
        });
Here is what I can see in the browser DOM elements list:
<svg width="500" height="500">
  <circle r="50" cx="60" cy="60" fill="red"></circle>
  <rect width="100" height="100" x="120" y="10" fill="blue"></rect>
</svg>

回答1:


Javascript creates elements in the HTML namespace by default, you need the SVG namespace for them to be interpreted correctly:

document.createElementNS('http://www.w3.org/2000/svg', d.shape);

Complete demo here.



来源:https://stackoverflow.com/questions/30064373/d3-does-not-render-or-paint-dom-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!