d3-force-grid
Version:
A force to snap nodes to a grid for the d3-force simulation engine.
78 lines (74 loc) • 2.52 kB
JavaScript
// Version 1.0.0 d3-force-grid - https://github.com/vasturiano/d3-force-grid
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.d3 = global.d3 || {}));
})(this, (function (exports) { 'use strict';
function grid () {
var step = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10;
var nDim,
dims,
nodes = [],
stepX = step,
stepY = step,
stepZ = step,
strength = 0.3,
considerAlpha = false;
function force(alpha) {
var acceleration = strength * (considerAlpha ? alpha : 1);
nodes.forEach(function (node) {
dims.forEach(function (_ref) {
var dim = _ref.dim,
v = _ref.v,
step = _ref.step;
var pos = node[dim];
var target = Math.round(pos / step) * step;
node[v] += (target - pos) * acceleration;
});
});
}
force.initialize = function (initNodes) {
nodes = initNodes;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
nDim = args.find(function (arg) {
return [1, 2, 3].includes(arg);
}) || 2;
dims = ['x', nDim > 1 ? 'y' : null, nDim > 2 ? 'z' : null].filter(function (d) {
return d;
}).map(function (dim) {
return {
dim: dim,
v: "v".concat(dim),
step: {
x: stepX,
y: stepY,
z: stepZ
}[dim]
};
});
};
force.step = function (_) {
return arguments.length ? (stepX = stepY = stepZ = _, force) : stepX;
};
force.stepX = function (_) {
return arguments.length ? (stepX = _, force) : stepX;
};
force.stepY = function (_) {
return arguments.length ? (stepY = _, force) : stepY;
};
force.stepZ = function (_) {
return arguments.length ? (stepZ = _, force) : stepZ;
};
force.strength = function (_) {
return arguments.length ? (strength = _, force) : strength;
};
force.considerAlpha = function (_) {
return arguments.length ? (considerAlpha = _, force) : considerAlpha;
};
return force;
}
exports.forceGrid = grid;
}));
//# sourceMappingURL=d3-force-grid.js.map