1
votes

I've already looked at this - SVG foreignObject not showing in Chrome

and it did not answer my question. I have text in a foreign object in SVG and it is not showing.

This is my code.

        var svg = d3.select("#chart").append("svg").attr('width', width).attr('height', height);

        var cell = svg.selectAll("g")
            .data(nodes)
            .enter().append("g")
            .attr("class", "cell");

        cell.append("rect")
            .attr("class", "node")
            .attr("x", function(d) { 
                return x(d.x); })
            .attr("y", function(d) { 
                return y2(d.y); })
            .attr("width", function(d) { 
                return x(d.dx); })
            .attr("height", function(d) { 
                return y2(d.dy); })
            .style("fill", function(d) { 
                var test = (d.children ? d : d.parent).name;
                console.log(test);
                return color(Math.random());; 
            })

        cell.append("foreignObject")
            .attr("class", "foreignObject")
            .attr("width", function(d) {
                return d.dx;
            })
            .attr("height", function(d){
                return d.dy;
            })
            .attr("transform", function(d) {
                return "translate(" + x(d.x + d.dx/2) + "," + (y2(d.y)) + ") rotate(90)";
            })
            .append("xhtml:body")
            .attr("class","label")
            .append("div")
            .text(function(d){
                return d.name;
            })
            .attr("text-anchor", "middle");

I have the text inside of a body tag (as the other answer says), but I still don't see the text. It looks like the container div has no height, although I'm explicitly setting the height.

What's going on?

2

2 Answers

0
votes

This worked.

Setting a width and height on the foreignObject with CSS.

.foreignObject {
    font: 9px sans-serif;
    text-overflow: ellipsis;
    text-align: left;
    word-wrap: break-word;
    height: 100px;
    width: 100px;
}
-3
votes

Before using <foreignObject> tag you need to include <switch> tag.

something that looks like this

<switch>
<foreingObject>
<body>
some code here
</body>
</foreingObject>
</switch>

This should work just fine with Chrome