Mathematics
Mathematics

Reputation: 7628

Adding text to rect not working

I am trying to add text to rect but it doesn't seem to be working, This is what I am trying,

var width = 600,
height = 600;
var margin = {top: -5, right: -5, bottom: -5, left: -5};

var zoom = d3.behavior.zoom()
    .scaleExtent([1, 15])
    .on("zoom", zoomed);

var svgContainer = d3.select("body").append("svg")
                                    .attr("width", width)
                                    .attr("height", height)
                                    .style("background-color", "black")
                                    .append("g")
                                    .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
                                    .call(zoom);

var zoomed = function () {
    svgContainer.attr("transform", "translate("+ d3.event.translate + ")scale(" + d3.event.scale + ")");
};

var zoom = d3.behavior.zoom()
.scaleExtent([1, 8])
.on("zoom", zoomed)
.size([width, height]);

svgContainer.call(zoom);

var rectangle1 = svgContainer.append("rect")
                            .attr("x", 0)
                            .attr("y", 0)
                            .attr("width", 100)
                            .attr("height", 100)
                            .attr("fill", "red")
                            .append("text")
                            .text("Hahaha");

Here's is fiddle for it - http://jsfiddle.net/nhe613kt/60/

Upvotes: 0

Views: 1223

Answers (1)

AJ_91
AJ_91

Reputation: 581

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

D3 Appending Text to a SVG Rectangle

svgContainer.append("text")
    .attr("id", "rectangleText")
    .attr("class", "visible")
    .attr("x", 10)
    .attr("y", 50)
    .attr("dy", ".35em")
.text("You're Welcome :)");

Instead of appending it to the rectangle append it to the object the rectangle is appended to :)

Fiddle : http://jsfiddle.net/nhe613kt/71/

Also, your dragging of the rectangle is a bit static, doesnt move correctly. You need to split your zoom function and create a drag function separately. Then append the dragged to the rectangle, and the zoomed to the SVG :)

Hope that helps

Upvotes: 2

Related Questions