【问题标题】:D3 Does not render or paint DOM elementD3 不渲染或绘制 DOM 元素
【发布时间】:2015-05-06 06:50:31
【问题描述】:

我正在尝试从不同形状的数组中绘制 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>

【问题讨论】:

    标签: d3.js


    【解决方案1】:

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

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

    完整的演示here

    【讨论】:

    • Lars 毫无疑问是一位超级巨星。你是大师先生。问题解决了。
    猜你喜欢
    • 2018-07-04
    • 1970-01-01
    • 2011-11-20
    • 2022-10-25
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多