Javascript:
$(document).ready(function() {
var systems = 'https://raw.githubusercontent.com/joeberthelot88/EVE-Online-Mapper/master/eveSystems.json?token=AWUj7mQ8T_6NBaRgIcz4Xz0KQd1SazMUks5ZjpeAwA%3D%3D';
var constellations = [20000441, 20000442, 20000443, 20000444, 20000445, 20000446, 20000447];
var arrayX = [];
var arrayY = [];
$.getJSON(systems, function(data) {
data.forEach(function(systemData) {
// Get data and build elements for each object found in constellations array
if(constellations.indexOf(systemData.constellation_id) > -1) {
// Simplify location coordinates
var x = systemData.position.x / 100000000000000;
var y = systemData.position.y / 100000000000000;
// Push coordinates to arrays
arrayX.push(x);
arrayY.push(y);
// Get the lowest coordinate values
var offsetX = Math.min.apply(Math, arrayX);
var offsetY = Math.min.apply(Math, arrayY);
// Set pixel offsets to center in the viewport
var coordX = x + offsetX;
var coordY = y + offsetY;
// Build SVG elements
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('id', systemData.name);
svg.setAttribute('title', systemData.name);
svg.setAttribute('class', 'system');
svg.setAttribute('constellation-id', systemData.constellation_id);
svg.setAttribute('style', 'margin-top:'+coordY+'px;margin-left:'+coordX+'px');
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
document.getElementById('container').appendChild(svg);
} else {
}
});
});
$(this.body).panzoom();
});
它的作用:
- 循环访问 JSON 对象
- 对于每个对象,它会查找该对象包含 constellation_id 的匹配项
- 如果找到匹配项,会将坐标推送到数组,然后将每个数组中的最小数字存储为变量
- 在每次循环期间,都会创建一个 SVG 元素
问题:
在创建 SVG 元素期间,我使用 coordX
和 coordY
变量设置 CSS 边距。相反,我需要将这些变量替换为新的 offsetX
和 offsetY
变量,但这不起作用,因为 offsetX 和 offsetY 变量未处于最终状态由于 arrayX 和 arrayY 数组仍在构建中。
基本上,我需要构建 offsetX 和 offsetY 变量,然后运行 SVG 创建。
最佳答案
此迭代可以分为两个循环,第一个循环是构建渲染数据所需的所有内容,然后是 svg 渲染循环本身。这种分割与 Flux/React 中惯用的渲染和状态更新分离相得益彰,这可能会让以后更容易切换到它们或类似的框架。
如果您可以避免 forEach
并使用没有副作用的函数,那就加分了。我会推荐 immutable.js
,因为它提供了许多有用的函数式实用程序,并提供不可变的数据结构,以及容器(列表、 map 等)的相等性检查(并用作键)。
另外,顺便说一句,我建议切换到 let
和 const
语法并使用箭头函数。
关于forEach 内的 Javascript 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45525860/