aug
aug

Reputation: 11714

D3 How to zoom in on SVG text that stays within an SVG Rectangle?

I am trying to zoom in on a rectangle that has text appended inside. I am using getBBox() to determine the size of the text and then drawing a rectangle based on the size of that text. From there I tried adding zoom/pan functionality.

Unfortunately when you zoom in, the text and rectangle do not scale the same way. When you zoom in, the text scales way too much and it does not stay within the rectangle. Actually it seems the rectangle only will encapsulate the text at the default zoom level.

http://jsfiddle.net/9cWWW/1/

I'm not sure if I should be scaling the rectangle or the text inside to the other. I'm trying to play around with the redraw function to see if I can transform the size with the current width of the text so I will update my jsfiddle if I get any progress. If anyone can give me some advice on this, I would really appreciate it.

Upvotes: 2

Views: 5140

Answers (1)

aug
aug

Reputation: 11714

Here is the new JSFiddle: http://jsfiddle.net/9cWWW/6/

Changes that needed to be made for this to work:

IE:

Apparently I needed to remove the extra <svg> element I had at the top when appending.

Firefox:

Apparently you need to set the width and height of the SVG as shown here:

var svg = d3.select("body").append("svg:svg").attr("height","100%").attr("width","100%")
            .call(d3.behavior.zoom().on("zoom", redraw))
              .append("g");

Thank you so much to gilly3 for telling me this.

Chrome:

Apparently you need to make sure you specify the font-size attribute:

var text = svg.append("svg:text")
    .attr("x", 480)
    .attr("y", 250)
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .attr("font-size", nodeFontSize + "px") //<-- added
    .text("This is the text I want to make zoomable");

Hope this helps everyone!

Upvotes: 3

Related Questions