2015-09-05 125 views
0

如何在矩形內添加多邊形?,下面是我有的代碼,但它沒有顯示矩形內的多邊形。你可以幫我嗎。d3.js在矩形內添加多邊形

var svgContainer = d3.select("body").append("svg") 

var rectangle = svgContainer.append("rect") 
           .style("stroke", "black") 
           .style("fill", "none") 
          .attr("x", 50) 
          .attr("y", 50) 
          .attr("width", 100) 
          .attr("height", 100); 


var cir = rectangle.append("polygon")  // attach a polygon 
    .style("stroke", "black") // colour the line 
    .style("fill", "none")  // remove any fill colour 
    .attr("points", "30,50,100,150,100,150"); // x,y points 

回答

1

您正在使用的矩形DOM這是不正確使多邊形 你應該多邊形連接到SVG 所以應該

svgContainer.append("polygon") 
下面

糾正代碼:

var svgContainer = d3.select("body").append("svg") 

var rectangle = svgContainer.append("rect") 
           .style("stroke", "black") 
           .style("fill", "none") 
          .attr("x", 50) 
          .attr("y", 50) 
          .attr("width", 100) 
          .attr("height", 100); 


var cir = svgContainer.append("polygon")  // attach a polygon to the svg 
    .style("stroke", "black") // colour the line 
    .style("fill", "none")  // remove any fill colour 
    .attr("points", "30,50,100,150,100,150"); // x,y points 

工作小提琴​​

要使多邊形出現在矩形內,您需要相應地提供多邊形點/座標。 只需使rect DOM元素中的多邊形不會使其顯示矩形。 希望這可以消除你的擔憂。

+0

感謝細節 - 西里爾。有沒有辦法我可以將三角形恰好放在矩形的中心。 – gorants

+0

@gorants你可以通過計算中心並提供數組中的點來確定任何三角形的中心點擊這裏查看我的演示http://jsfiddle.net/pgerw8va/2/ 現在你將不得不編寫一個算法來計算一箇中心點數字。 – Cyril

+0

謝謝Cyril ..讚賞你的幫助 – gorants