radial.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import constant from "./constant.js";
  2. export default function(radius, x, y) {
  3. var nodes,
  4. strength = constant(0.1),
  5. strengths,
  6. radiuses;
  7. if (typeof radius !== "function") radius = constant(+radius);
  8. if (x == null) x = 0;
  9. if (y == null) y = 0;
  10. function force(alpha) {
  11. for (var i = 0, n = nodes.length; i < n; ++i) {
  12. var node = nodes[i],
  13. dx = node.x - x || 1e-6,
  14. dy = node.y - y || 1e-6,
  15. r = Math.sqrt(dx * dx + dy * dy),
  16. k = (radiuses[i] - r) * strengths[i] * alpha / r;
  17. node.vx += dx * k;
  18. node.vy += dy * k;
  19. }
  20. }
  21. function initialize() {
  22. if (!nodes) return;
  23. var i, n = nodes.length;
  24. strengths = new Array(n);
  25. radiuses = new Array(n);
  26. for (i = 0; i < n; ++i) {
  27. radiuses[i] = +radius(nodes[i], i, nodes);
  28. strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes);
  29. }
  30. }
  31. force.initialize = function(_) {
  32. nodes = _, initialize();
  33. };
  34. force.strength = function(_) {
  35. return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  36. };
  37. force.radius = function(_) {
  38. return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
  39. };
  40. force.x = function(_) {
  41. return arguments.length ? (x = +_, force) : x;
  42. };
  43. force.y = function(_) {
  44. return arguments.length ? (y = +_, force) : y;
  45. };
  46. return force;
  47. }