2014-07-26 129 views
1

我是d3.js的初学者,我想添加一些文本和矩形内部的矩形。d3将文本添加到SVG矩形

这里是我的代码:

  if (!_svg) { 
      _svg = d3.select("#col1").append("svg") 
        .attr("height", _height - 2) 
        .attr("width", _width - 2); 
     } 

     _svg.append("text").attr({ 
      id: "leftDomainName", 
      x: d3.select("svg").attr("width")/14, 
      y: d3.select("svg").attr("height")/2, 
      class: "vertical-text" 
     }).text("Business Development"); 

     var g = _svg.append("g").attr("transform", function (d, i) { 
      return "translate(0,0)"; 
     }).attr("clip-path", "url(#body-clip)"); 


     var mainBox = g.append("rect").attr({ 
      id: "mainBox", 
      x: d3.select("svg").attr("width")/8, 
      y: 3, 
      width: _width - 60, 
      height: _height/3, 
      fill: "#D7FFEC" 
     }); 

     mainBox.append("text").text("sample!!!"); 
     mainBox.append("rect").attr({ 
      x: 50, 
      y: 50, 
      width: _width - 60, 
      height: _height/3, 
      fill: "red" 
     }); 

我想添加一个文本和矩形SVG内mainBox。在铬develper工具,我可以看到他们的加入,但也有不

enter image description here

什么是我错了吗? 谢谢

我追加克至mainBox,然后我的元素追加到g,但它没有工作

  var innerG = mainBox.append("g"); 

     innerG.append("text").text("sample!!!"); 
     innerG.append("rect").attr({ 
      x: 50, 
      y: 50, 
      width: _width - 60, 
      height: _height/3, 
      fill: "red" 
     }); 

enter image description here

回答

6

不能添加到textrect SVG中的元素。为了达到你想要什么,添加包含两个textrect一个g元素:你的意思是mainBox内的

g.append("text").text("sample!!!"); 

代替

mainBox.append("text").text("sample!!!"); 
+0

?我做到了,但没有奏效。我将我的新代码添加到问题部分 – farhad

+0

嗯,它看起来像你已经将所有这些附加到另一个'rect'元素。这不会出于同样的原因 - 如果你想分组元素,使用'g'元素。 –

+0

您的评论后,我分组他们,但它没有work.please看问题的粗体和斜体行 – farhad