D3不渲染或绘制DOM元素 [英] D3 Does not render or paint DOM element

查看:34
本文介绍了D3不渲染或绘制DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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/

谢谢

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>

推荐答案

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

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);

完整演示此处.

这篇关于D3不渲染或绘制DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆