简体   繁体   中英

How to add foreignObject to a d3 circle?

I want to display "complexe" div inside a d3 circle . As I understand, I can't add a div inside an svg element unless I use the foreignObject element.

I was able to add a div inside a pure d3 svg element, but I have no luck with a d3 circle element.

Here a JSFiddle example that shows a circle element and what I tried to do.

Assuming you accept adding foreign object with a d3 syntax, this code should fit your need :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM