2015-09-05 55 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