gpt4 book ai didi

javascript - 随机放置 svg 多边形

转载 作者:行者123 更新时间:2023-12-03 06:26:49 25 4
gpt4 key购买 nike

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

$(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" );
};
});
<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>

最佳答案

您可以将要克隆的多边形存储在 defs 元素中。通过使用边界框和翻译属性,可以将每个克隆元素定位在您想要的位置。请参阅下面的示例:

<!DOCTYPE HTML>

<html>

<head>
<title>Replicate Polygons</title>
</head>

<body onload=placePolys()>
<svg id=mySVG width=500 height=500>
<defs id=myClones>
<polygon id="poly1" points="20,50 10,50 30,60" fill="#ed078d" />
<polygon id="poly2" points="60,10 70,30 80,20" fill="#d71f39" />
<polygon id="poly3" points="40,80 60,90,60,100" fill="#f78d37" />
<polygon id="poly4" points="50,50 50,60 80,50" fill="#c52031" />
</defs>
</svg>


</body>
<script>
var locArray=[]
locArray[0]=["poly2",120,60]
locArray[1]=["poly2",60,50]
locArray[2]=["poly3",200,90]
locArray[3]=["poly4",320,340]
locArray[4]=["poly1",400,100]
locArray[5]=["poly3",100,120]
locArray[6]=["poly1",440,50]
locArray[7]=["poly4",120,300]
locArray[8]=["poly4",440,440]
locArray[9]=["poly3",100,300]
locArray[10]=["poly3",450,300]

function placePolys()
{
for(var k=0;k<locArray.length;k++)
{
var loc=locArray[k]
var cloneMe=loc[0]
var clone=document.getElementById(cloneMe).cloneNode(true)
clone.setAttribute("id","clone"+k)
var x=loc[1]
var y=loc[2]
mySVG.appendChild(clone)
var bb=clone.getBBox()
var bbx=bb.x
var bby=bb.y
var bbw=bb.width
var bbh=bb.height
var cx=bbx+.5*bbw
var cy=bby+.5*bbh
var transX=x-cx
var transY=y-cy
clone.setAttribute("transform","translate("+transX+" "+transY+")")
}
}

</script>

</html>

关于javascript - 随机放置 svg 多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38611975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com