2016-08-30 14 views
5

Zaprogramowałem funkcję, która obraca obiekty wokół głównego obiektu, np. Jak planety obracają się wokół Słońca.Dynamicznie dodawaj nowe elementy w funkcji

Próbuję dynamicznie dodawać nowe planety w moim małym Układzie Słonecznym za pomocą jednego kliknięcia przycisku. Wszystkie są elementami SVG. Mam problem z wypracowaniem sposobu, w jaki mogę dynamicznie generować nowe elementy, które obracają się wokół Słońca dzięki mojej funkcji rotation(coorX, coorY, object). Wszyscy musieliby być dynamicznie nazywane i dynamicznie pozycjonowane, to jest dla mnie zbyt trudne.

Jak powinien wyglądać mój kod, aby móc to osiągnąć? Z góry dziękujemy za pomoc/wskazówki.

Oto mój kod:

var objectX = "black"; 
 
function addObject(){ 
 
    objectX = "blue"; 
 
} 
 

 
function rotation(coorX, coorY, object) { 
 
\t object.side += (1.0/object.speed); 
 
\t var ang = object.side * 2.0 * Math.PI/180.0; 
 
\t var r = object.spin; 
 
    
 
\t return { 
 
\t \t x: Math.cos(ang) * r - Math.sin(ang) * r + coorX, 
 
\t \t y: Math.sin(ang) * r + Math.cos(ang) * r + coorY 
 
\t }; 
 
    } 
 
    
 
    function rotationball (circle) { 
 
\t var x, y, x_black, y_black, e, newpos; 
 
\t e = document.getElementById (circle); 
 
\t x_black = parseFloat (document.getElementById (objectX).getAttribute ("cx")); 
 
\t y_black = parseFloat (document.getElementById (objectX).getAttribute ("cy")); 
 
\t newpos = rotation(x_black, y_black, ball[circle]); 
 
    
 
\t e.setAttribute ("cx", newpos.x); 
 
\t e.setAttribute ("cy", newpos.y); 
 
\t } 
 
    
 
    var ball = { 
 
    blue: \t {speed: 1.2, \t spin: 100, \t side: 0.0} , 
 
    red: \t {speed: 1.2, \t spin: 200, \t side: 0.0} 
 
\t }; 
 
    
 
    function animate() { 
 
    \t rotationball("blue"); 
 
    \t rotationball("red"); 
 
\t }  
 

 
var animateInterval = setInterval(animate, 1000/60);
.st0{fill:black;} 
 
.st1{fill:blue;} 
 
.st2{fill:red;}
<div class="spinning"> <svg xmlns="http://www.w3.org/2000/svg" id="solly" viewBox="0 0 1000 600"><g id="Sun2"> 
 
\t \t <circle id="black" class="st0" cx="500" cy="300.8" r="10"/> 
 
\t \t <circle id="blue" class="st1" cx="375.4" cy="289.7" r="10"/> \t 
 
    <circle id="red" class="st2" cx="375.4" cy="289.7" r="10"/> \t 
 
    
 
</div> 
 
<button type="button" onclick="addObject()"> 
 
button 
 
</button>
PS: Ja też będzie program, który każdy dodany planeta będzie umieszczony nieco dalej od punktu centralnego (słońca) niż poprzednio dodanego planety.

+1

Pełna treść pytania musi być ** na ** Twoje pytanie, nie tylko powiązane. Linki gniją, sprawiając, że pytanie i jego odpowiedzi stają się bezużyteczne dla ludzi w przyszłości, a ludzie nie powinni wychodzić z witryny, aby ci pomóc.Umieść [mcve] ** w ** pytaniu, najlepiej używając Fragmentów stosu (przycisk '<>' przycisk paska narzędzi), aby umożliwić jego uruchamianie. Więcej: [* Jak zadać dobre pytanie? *] (/ Help/how-to-ask) –

+1

Wygląda na to, że zessx był na tyle uprzejmy, aby to naprawić. –

Odpowiedz

5

Jesteś na dobrej drodze dzięki Twojemu obiektowi ball (chociaż nazwałbym go balls). Do dynamicznego tworzenia elementu circle to zrobić:

var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle"); 

Następnie należy ustawić jego atrybuty (circle.setAttribute) i dołączyć go do elementu id="Sun2".

Oto makeBall funkcja, która robi to na podstawie obiektu specyfikacji mijamy, w którym ma dwie podobiekty: element, który definiuje element, a animation który definiuje animację:

function makeBall(spec) { 
    // Create the element 
    var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle"); 
    // Set its various attributes 
    ["id", "cx", "cy", "r", "class"].forEach(function(attrName) { 
    circle.setAttribute(attrName, spec.element[attrName]); 
    }); 
    // Add it to the sun 
    document.getElementById("Sun2").appendChild(circle); 
    // Remember its animation settings in `ball` 
    ball[spec.element.id] = spec.animation; 
} 

Następnie użyć to tak:

makeBall({ 
    element: {id: "blue", class: "st1", cx: "375.4", cy: "289.7", r: "10"}, 
    animation: {speed: 1.2, spin: 100, side: 0.0} 
}); 

ostatni kawałek jest zastąpienie ożywione z czymś, co działa dynamicznie z właściwościami wewnątrz ball:

function animate() { 
    Object.keys(ball).forEach(function(id) { 
    rotationball(id); 
    }); 
} 

Oto przykład usuwania blue i red ze znacznikami i dodając je dynamicznie, kiedy zacząć. Ja również pozbyć objectX i sprawiają, że rotacja zawsze być w stosunku do black i związał się kilka pól do wykorzystania podczas dodawania nowej piłki:

var ball = {}; 
 

 
makeBall({ 
 
    element: {id: "blue", class: "st1", r: "10"}, 
 
    animation: {speed: 1.2, spin: 20, side: 0.0} 
 
}); 
 
makeBall({ 
 
    element: {id: "red", class: "st2", r: "10"}, 
 
    animation: {speed: 1.2, spin: 40, side: 120.0} 
 
}); 
 
makeBall({ 
 
    element: {id: "yellow", class: "st3", r: "10"}, 
 
    animation: {speed: 1.2, spin: 60, side: 240.0} 
 
}); 
 

 
function makeBall(spec) { 
 
    // Create the element 
 
    var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle"); 
 
    // Set its various attributes 
 
    ["id", "cx", "cy", "r", "class"].forEach(function(attrName) { 
 
    if (spec.element[attrName]) { 
 
     circle.setAttribute(attrName, spec.element[attrName]); 
 
    } 
 
    }); 
 
    // Add it to the sun 
 
    document.getElementById("Sun2").appendChild(circle); 
 
    // Remember its animation settings in `ball` 
 
    ball[spec.element.id] = spec.animation; 
 
} 
 

 
function addObject() { 
 
    // Create a spec to use with makeBall from the fields 
 
    var spec = { 
 
    element: { 
 
     id: document.getElementById("new-id").value, 
 
     class: document.getElementById("new-class").value, 
 
     r: parseFloat(document.getElementById("new-r").value) 
 
    }, 
 
    animation: { 
 
     speed: parseFloat(document.getElementById("new-speed").value), 
 
     spin: parseFloat(document.getElementById("new-spin").value), 
 
     side: parseFloat(document.getElementById("new-side").value) 
 
    } 
 
    }; 
 
    // Some minimal validation 
 
    if (!spec.element.id || !spec.element.r || !spec.animation.speed || !spec.animation.spin || isNaN(spec.animation.side)) { 
 
    alert("Need all values to add a ball"); 
 
    } else if (ball[spec.element.id]) { 
 
    alert("There is already a ball '" + spec.element.id + "'"); 
 
    } else { 
 
    // Do it! 
 
    makeBall(spec); 
 
    } 
 
} 
 

 
function rotation(coorX, coorY, object) { 
 
    object.side += (1.0/object.speed); 
 
    var ang = object.side * 2.0 * Math.PI/180.0; 
 
    var r = object.spin; 
 

 
    return { 
 
    x: Math.cos(ang) * r - Math.sin(ang) * r + coorX, 
 
    y: Math.sin(ang) * r + Math.cos(ang) * r + coorY 
 
    }; 
 
} 
 

 
function rotationball(circle) { 
 
    var x, y, x_black, y_black, e, newpos, black; 
 

 
    // We always rotate around black 
 
    black = document.getElementById("black"); 
 
    
 
    // Get this circle and update its position 
 
    e = document.getElementById(circle); 
 
    x_black = parseFloat(black.getAttribute("cx")); 
 
    y_black = parseFloat(black.getAttribute("cy")); 
 
    newpos = rotation(x_black, y_black, ball[circle]); 
 

 
    e.setAttribute("cx", newpos.x); 
 
    e.setAttribute("cy", newpos.y); 
 
} 
 

 
function animate() { 
 
    Object.keys(ball).forEach(function(id) { 
 
    rotationball(id); 
 
    }); 
 
} 
 

 
var animateInterval = setInterval(animate, 1000/60);
.st0 { 
 
    fill: black; 
 
} 
 
.st1 { 
 
    fill: blue; 
 
} 
 
.st2 { 
 
    fill: red; 
 
} 
 
.st3 { 
 
    fill: yellow; 
 
} 
 
.st4 { 
 
    fill: orange; 
 
}
<div>Add ball: 
 
    <label> 
 
    ID: <input type="text" id="new-id" value="newball"> 
 
    </label> 
 
    <label> 
 
    R: <input type="text" id="new-r" value="10"> 
 
    </label> 
 
    <label> 
 
    Speed: <input type="text" id="new-speed" value="1.2"> 
 
    </label> 
 
    <label> 
 
    Spin: <input type="text" id="new-spin" value="80"> 
 
    </label> 
 
    <label> 
 
    Side: <input type="text" id="new-side" value="0.0"> 
 
    </label> 
 
    <label> 
 
    Class: <input type="text" id="new-class" value="st4"> 
 
    </label> 
 
    <button type="button" onclick="addObject()"> 
 
    Make Ball 
 
    </button> 
 
</div> 
 

 
<div class="spinning"> 
 
    <svg xmlns="http://www.w3.org/2000/svg" id="solly" viewBox="0 0 1000 600"> 
 
    <g id="Sun2"> 
 
     <circle id="black" class="st0" cx="500" cy="300.8" r="10" /> 
 
    </g> 
 
    </svg> 
 
</div>


marginesie: Możesz spojrzeć na używanie requestAnimationFrame zamiast setInterval.

Nota boczna 2: Z tego co wiem, to, co nazwałaś spin, jest w rzeczywistości odległością od środka (np. Promień okręgu, który każda piłka opisuje wokół czarnej kulki).

+0

Cześć, dziękuję za pomoc. Ale widzę, że ten fragment nie działa tak, jak bym tego chciał. W rzeczywistości nie doda się nowej planety, gdy kliknę przycisk, lub dzieje się to poza rozmiarem ekranu. Ponadto sprawia, że ​​rotacja idzie o wiele szybciej, podczas gdy ja chcę, aby pozostała taka sama. Co musiałoby zostać zmienione? – Zhyohzhy

+0

@Zhyohzhy: Jak już powiedziałem w odpowiedzi, pokazałem ci, jak utworzyć element dynamicznie, ale zostawiłem go tobie, aby podłączyć przycisk, aby to zrobić z wartościami dynamicznymi. Wystarczy odpowiedzieć na kliknięcie przycisku, wywołując 'makeBall' z nowymi wartościami. Re szybkość animacji: Używa tylko tych samych ustawień, które zrobił twój oryginalny kod. –

+0

Jakoś nie mogę zaimplementować twojego kodu do mojego bez problemu. Nadal uczę się ogólnie programowania, czy mógłbyś pokazać swój kod z moim? – Zhyohzhy

Powiązane problemy