2016-08-31 9 views
10

어떻게 이와 같은 JSON 데이터를 기반으로, 코드 조각에서 아래 별 시스템 (이것에 의해 내가 행성을 의미) 새로운 요소를 추가 할 :추가 객체

 [{ 
      "rowid": 1, 
      "Radius size": 3 , 
      "Distance": 110 pixels, 
     }, 
     { 
      "rowid": 2, 
      "Size": 2.5, 
      "Distance": 120 pixels, 
     }] 

각 행 ID는 크기와 위치가 고유 한 행성입니다. 거리는 물론 페이지의 중앙에있는 태양 요소로부터 행성의 거리를 기반으로합니다. 행성 당 거리는 다른 각도를 가져야합니다. 그렇지 않으면 모든 행성이 완벽하게 정렬됩니다 (비현실적입니다). 이것이 어떻게 달성 될 수 있는지에 대한 아이디어가 있습니까?

var ball = {}; 
 

 
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: 2, 
 
     spin: 30, 
 
     side: 40 
 
    } 
 
    }; 
 
    // 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: yellow; 
 
} 
 

 
.st1 { 
 
    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="st1"> 
 
    </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>

는 자신의 ID가있는 경우 새 공 (행성)을 추가 코드 (전체 광산되지 않음)입니다. JSON 데이터 세트로 바꾸고 싶습니다.

편집 : 다음은 두 레코드의 원본 예입니다. 보시다시피 더 많은 중복 속성을 제공합니다. 정말 각 레코드에서 필요한 모든 크기 (지구 반경 [목성 반경]와 거리이다 (거리 [PC]를). 거리가 픽셀로 변환 될 필요가있을 것이다, 크기는 까다 롭습니다.

 [{ 
     "rowid": 1, 
     "Host name": "TrES-3", 
     "Number of Planets in System": 1, 
     "Planet Mass or M*sin(i)[Jupiter mass]": 1.91, 
     "Planet Radius [Jupiter radii]": 1.336, 
     "Planet Density [g": { 
      "cm**3]": 0.994 
     }, 
     "Distance [pc]": 228, 
     "Effective Temperature [K]": 5650, 
     "Date of Last Update": "5/14/2014" 
    }, 
    { 
     "rowid": 2, 
     "Host name": "UZ For", 
     "Number of Planets in System": 2, 
     "Planet Mass or M*sin(i)[Jupiter mass]": 6.3, 
     "Planet Radius [Jupiter radii]": null, 
     "Planet Density [g": { 
      "cm**3]": null 
     }, 
     "Distance [pc]": null, 
     "Effective Temperature [K]": null, 
     "Date of Last Update": "5/14/2014" 
    }] 
+0

우수 질문! – christopher

+0

충분히 재미있을 것 같습니다. 누군가가 당신을 도울 수 있기를 바랍니다. – JohnMichael

+1

JSON이 무엇인지에 대해 교육 해주십시오. 서버와 같은 정보를 교환하기위한 ** 문자열 기반 형식 **입니다. 그것은 ** 아닙니다 ** 귀하의 질문에 같은 일반적인 자바 스크립트 개체를 참조하는 단어. 그러한 잘못된 용어로 자신을 포함한 모든 사람을 혼란스럽게하지 않도록 노력하십시오. –

답변

1

그것은 실제로 매우 간단합니다 :

HTML을 읽으면 "공 만들기"버튼을 클릭하면 addObject()가 호출됨을 알 수 있습니다. 따라서 JS 코드에서 해당 함수를 확인하십시오 .addObject()는 값 입력 필드에서 spec이라는 객체로 호출 한 다음 makeBall (spec)을 호출합니다.

해야 할 일은 provi 각 JSON 데이터에 대해 makeBall 함수와 완전히 동일한 데이터 오브젝트 스펙.

function addObjectsFromJson(json){ 
    // using try catch block because JSON.parse will throw an error if the json is malformed 
    try{ 
     var array = JSON.parse(json); 
     for(var i = 0; i < array.length; i++){ 
      var planet = array[i]; 
      // create a spec to use with makeBall from the json 
      var spec = { 
       element: { 
        id: planet.rowid, 
        // you don't provide a style class in your json yet, using yellow as default 
        class: 'st0', 
        // your json must have a standard property for radius, 
        // currently you have "Radius size" (is wrong since 
        // properties cannot have spaces) and "Size" 
        r: planet["Planet Radius [Jupiter radii]"] 
       }, 
       animation: { 
        speed: 2, 
        spin: 30, 
        side: planet["Distance [pc]"] 
       } 
      }; 
      makeBall(spec); 
     } 
    }catch(e){ 
     console.log('error: ' + e); 
    } 
} 

makeBall() 함수에 거리를 추가하는 속성이 표시되지 않습니다. jQuery로 아약스를 통해

핸들 JSON :

// assuming your local server runs on port 8080 
$.getJSON('localhost:8080/path/to/your/file', function (json) { 
    // since we use getJSON, it is already parsed and a javascript object 
    // additional parsing inside the addObjectsFromJson function is not necassary 
    // and would throw an error 
    addObjectsFromJson(json); 
}); 

function addObjectsFromJson(json) { 
    for (var i = 0; i < json.length; i++) { 
     var planet = json[i]; 
     // create a spec to use with makeBall from the json 
     var spec = { 
      element: { 
       id: planet.rowid, 
       // you don't provide a style class in your json yet, using yellow as default 
       class: 'st0', 
       // your json must have a standard property for radius, 
       // currently you have "Radius size" (is wrong since properties cannot have spaces) and "Size" 
        r: planet["Planet Radius [Jupiter radii]"] 
       }, 
       animation: { 
        speed: 2, 
        spin: 30, 
        side: planet["Distance [pc]"] 
     }; 
     makeBall(spec); 
    } 
} 
+0

함수는 JSON 데이터를 어떻게 검색합니까? 데이터가 실제로 수천 개의 레코드로 구성된 긴 .json 파일 인 경우 어떻게 될까요? 나는 사람들의 생각을 빨리 이해할 수 있도록 단지 한 켤레를 가져다가 맨손으로 본질적으로 다시 썼다. 예상했던대로 JSON을 다루는 데 너무 익숙하지 않아서 속성에 공백이있을 수 없다는 것을 예를 들어 알지 못했습니다. 그들이 원래 본 모습을 두 가지 기록으로 보여 주어야합니까? – Zhyohzhy

+0

예. JSON 데이터를 어떻게 제공합니까? – Danmoreng

+0

요청 당 두 개의 레코드로 내 질문을 업데이트했습니다. 또한 HTML 페이지와 동일한 폴더에있는 .json 파일을 검색하여 JSON 데이터를 제공합니다. 나는 로컬 서버에서 일한다. – Zhyohzhy