D3不渲染或绘制DOM元素

时间:2015-05-05 22:35:23

标签: d3.js

我试图从不同形状的数组中绘制SVG元素。我可以看到所有形状成功添加到文档中,但我看不到它们在屏幕上呈现。有趣的是,如果我只是尝试从浏览器的DOM浏览器(在我的案例中为Chrome)中编辑HTML元素(不进行任何更改),则会按预期绘制形状。有什么建议在这里做错了吗?

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

由于



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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

默认情况下,Javascript在HTML命名空间中创建元素,您需要SVG命名空间才能正确解释它们:

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

完整演示here