2014-07-26 130 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