随机放置svg多边形

时间:2016-07-27 11:42:31

标签: javascript jquery svg polygon snap.svg

我有一个svg多边形,我想动态多次复制它们。所以我面临的问题是当我复制它们时,我应该如何复制这些点。 我没有硬编码数组中的点,而是希望它们是动态生成的。请帮帮我



$(document).ready(function() {
  var polyarray= {
    "polyobj": [{
      "id": 0,
      "name": 'Poly',
      "points":'20,10 30,30 30,20',
      "color":'#ed078d'
    },{
      "id": 1,
      "name": 'Poly1',
      "points":'20,50 10,50 30,60',
      "color": '#d71f39'
    },{
      "id": 2,
      "name": 'Poly2',
      "points":'60,10 70,30 80,20',
      "color":'#ed4a39'
    },{
      "id": 3,
      "name": 'Poly3',
      "points":'40,80 60,90,60,100',
      "color": '#f78d37'
    },{
      "id": 4,
      "name": 'Poly4',
      "points":'50,50 50,60 80,50',
      "color": '#c52031'
    }]
  }

  for (i = 0; i < polyarray.polyobj.length; i++) {
    var color = polyarray.polyobj[i].color;  
               
    var nowCloned = $( "#main-0" ).clone();
       
    nowCloned[0].id = "main-"+(i);
    var nc = "clip"+(i+1);

    var fnow = nowCloned.find('polygon')
      fnow.attr("id",nc);
      fnow.css({"fill":color});
      fnow.attr("points",polyarray.polyobj[i].points);    

    nowCloned.appendTo( "#Layer_1" );           
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg id="Layer_1" class="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 324.61 150.83">
  <g id="main-0" style="position:absolute; top:-899px;">
    <polygon points="" id="poly" />
  </g>
</svg>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以存储要在defs元素中克隆的多边形。通过使用边界框和translate属性,每个克隆元素都可以位于您想要的点。 请参阅以下示例:

&#13;
&#13;
M.*B
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以执行以下操作:

  function createNewPolyPoint(offset) {
                var pageHeight = $(window).height() - offset,
                    pageWidth = $(window).width() - offset,
                    randomX = Math.floor(Math.random() * pageHeight),
                    randomY = Math.floor(Math.random() * pageWidth);
                return [randomX, randomY];
            }

您可以为要绘制的每个多边形获得3组随机点,然后在附加之前将它们添加到多边形阵列结构中。