基于
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,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"
}]
解决方法
其实很简单:
如果您阅读HTML,您会注意到点击“Make Ball”按钮将调用addobject().所以你去检查JS代码中的那个函数.
addobject()简单地将输入域中的值解析为一个名为spec的对象,然后调用makeBall(spec).
您需要做的是为每个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,side: planet["distance [pc]"]
}
};
makeBall(spec);
}
}catch(e){
console.log('error: ' + e);
}
}
我在makeBall()函数中看不到添加一个距离的属性.
通过jQuery处理JSON通过jQuery:
// 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,using yellow as default
class: 'st0',// currently you have "Radius size" (is wrong since properties cannot have spaces) and "Size"
r: planet["Planet Radius [Jupiter radii]"]
},side: planet["distance [pc]"]
};
makeBall(spec);
}
}