如何将ForeignObject添加到d3圆?

时间:2018-07-04 15:03:02

标签: javascript d3.js

我想在div内显示“复杂” d3 circle。据我了解,除非使用div元素,否则无法在svg元素内添加foreignObject

我能够在纯div元素内添加d3 svg,但是我对d3 circle元素没有好运。

Here a JSFiddle example,其中显示了一个圆形元素以及我尝试做的事情。

1 个答案:

答案 0 :(得分:0)

假设您接受使用d3语法添加异物,则此代码应符合您的需求:

var ns = 'http://www.w3.org/TR/SVG11/';

var cont = d3.select("#container")
.append("svg")
.attr("xmlns",ns)
.attr("width", "400px")
.attr("height", "400px")
.attr("transform", "translate(100,100)")
;

var circle = cont.append("circle")
.attr("xmlns",ns)
.attr("id", "svg-div")
.attr("r","200")
.attr("fill", "red")
.attr("transform", "translate(200,200)")
;

var mainDiv = document.createElement('div');
mainDiv.innerHTML = 'Hello World';
mainDiv.style.background = "#000";
mainDiv.style.color = "#fff";
mainDiv.style.width = '50px';
mainDiv.style.height = '50px';

var numUsers = document.createElement("div");
numUsers.innerHTML = 5;
numUsers.style.display = 'inline';

var userIcon = document.createElement("img");
userIcon.src = "https://cdn1.iconfinder.com/data/icons/freeline/32/account_friend_human_man_member_person_profile_user_users-512.png";
userIcon.style.width = '12px';
userIcon.style.height = '12px';
userIcon.style.display = 'inline';

d3.select("svg").append("foreignObject")
            .attr("width", 100)
            .attr("height", 100)
            .attr("transform", "translate(200,200)")
            .append("xhtml:div")
            .html("5 ")
            .append('xhtml:img').attr('src','https://cdn1.iconfinder.com/data/icons/freeline/32/account_friend_human_man_member_person_profile_user_users-512.png')
            .attr("height","12px")
            .attr("width","12px");

var userDiv = document.createElement("div");
userDiv.appendChild(numUsers);
userDiv.appendChild(userIcon);

mainDiv.appendChild(userDiv);

var foreignObject = document.createElementNS( ns, 'foreignObject');
foreignObject.setAttribute('height', 100);
foreignObject.setAttribute('width', 100);
foreignObject.appendChild( mainDiv ); 

var svg = document.querySelector( '#svg-div' );
svg.appendChild(foreignObject);