JS -不能增加循环内的旋转属性?



目前所有的圆(原子)都是放在彼此的顶部。

我正在尝试增加一个特定的属性,以便圆圈(原子)从彼此的对面开始。在我的小提琴中,我正在创建SVG,并试图在每个循环中设置不同的旋转。

尝试:试图增加使用++和+=,虽然我似乎不能以编程方式添加每个原子之间的分离等量。还尝试添加一个数组的期望值,可以添加到旋转属性,但最终这些值会改变,因为原子的数量会改变。

这是我的工作JS小提琴:

https://jsfiddle.net/hab_1/qj9rwdmf/5/

let mainAtom = function(xPos, yPos, name){
for(i = 0; i < ring; i++){
var mainAtom = document.createElementNS('http://www.w3.org/2000/svg','circle');
mainAtom.setAttribute('cx', xPos);
mainAtom.setAttribute('cy', yPos);             
mainAtom.setAttribute('r', '5');
mainAtom.setAttribute('fill', atomFillColor);
mainAtom.setAttribute('stroke', atomStrokeColor);
mainAtom.setAttribute('stroke-width', '3');
mainAtom.setAttribute('z-index', '2');
// mainAtom.setAttribute('rotate', '36');
/*   const name = [" one", " two", " three"]   */
mainAtom.setAttribute('class', 'atom' + " " + name + " " + i) 
var svg = document.getElementById('svgx'); 
svg.appendChild(mainAtom); 
}

}

问题:是否有一种方法可以均匀地间隔创造的圆圈(原子),而不是放在彼此的顶部?

如果我正确理解了你的问题,你需要使用三角函数为每个原子分配正确的坐标(而不是试图旋转它)。这应该给你一个想法:

rings =[2, 8, 18, 32, 32, 18, 8]
rings.forEach(ring => {
let mainRingStrokeColor = "orange"
let mainRing = function(xPos, yPos, r) { 
let mainRing = document.createElementNS('http://www.w3.org/2000/svg','circle');
mainRing.setAttribute('cx', xPos);
mainRing.setAttribute('cy', yPos);  
mainRing.setAttribute('r', r);
mainRing.setAttribute('fill', 'rgba(0,0,0,0)');
mainRing.setAttribute('stroke', mainRingStrokeColor);
mainRing.setAttribute('stroke-width', '3');
let svg = document.getElementById('svgx');
svg.appendChild(mainRing); }

let atomFillColor = "white"
let atomStrokeColor = "orange"

let mainAtom = function(xPos, yPos, r, name){
for(i = 0; i < ring; i++){
var mainAtom = document.createElementNS('http://www.w3.org/2000/svg','circle');
mainAtom.setAttribute('cx', xPos + r * Math.cos((2 * Math.PI * i)/ring));
mainAtom.setAttribute('cy', yPos + r * Math.sin((2 * Math.PI * i)/ring));
//mainAtom.setAttribute('cx', xPos);
//mainAtom.setAttribute('cy', yPos);
mainAtom.setAttribute('r', '5');
mainAtom.setAttribute('fill', atomFillColor);
mainAtom.setAttribute('stroke', atomStrokeColor);
mainAtom.setAttribute('stroke-width', '3');
mainAtom.setAttribute('z-index', '2');
//mainAtom.setAttribute('rotate', '180deg');
/*   const name = [" one", " two", " three"]   */
mainAtom.setAttribute('class', 'atom' + " " + name + " " + i) 
var svg = document.getElementById('svgx'); 
svg.appendChild(mainAtom); 
}
} 

//create atoms and rings
if(ring <= 2){
mainRing(120, 120, 30) 
mainAtom(120, 120, 30, "orbit1")
} else if (ring <= 8 && ring > 2 ) {
mainRing(120, 120, 50)
mainAtom(120, 120, 50, "orbit2")
}   else if (ring <= 18 && ring > 8) {
mainRing(120, 120, 70)
mainAtom(120, 120, 70, "orbit3")
mainRing(120, 120, 90)
mainAtom(120, 120, 90, "orbit4")
}

})

https://jsfiddle.net/2uq14gx9/36/

最新更新