shapes.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import intersectRect from './intersect/intersect-rect'
  2. import intersectEllipse from './intersect/intersect-ellipse'
  3. import intersectCircle from './intersect/intersect-circle'
  4. import intersectPolygon from './intersect/intersect-polygon'
  5. function rect (parent, bbox, node) {
  6. const shapeSvg = parent.insert('rect', ':first-child')
  7. .attr('rx', node.rx)
  8. .attr('ry', node.ry)
  9. .attr('x', -bbox.width / 2)
  10. .attr('y', -bbox.height / 2)
  11. .attr('width', bbox.width)
  12. .attr('height', bbox.height)
  13. node.intersect = function (point) {
  14. return intersectRect(node, point)
  15. }
  16. return shapeSvg
  17. }
  18. function ellipse (parent, bbox, node) {
  19. const rx = bbox.width / 2
  20. const ry = bbox.height / 2
  21. const shapeSvg = parent.insert('ellipse', ':first-child')
  22. .attr('x', -bbox.width / 2)
  23. .attr('y', -bbox.height / 2)
  24. .attr('rx', rx)
  25. .attr('ry', ry)
  26. node.intersect = function (point) {
  27. return intersectEllipse(node, rx, ry, point)
  28. }
  29. return shapeSvg
  30. }
  31. function circle (parent, bbox, node) {
  32. const r = Math.max(bbox.width, bbox.height) / 2
  33. const shapeSvg = parent.insert('circle', ':first-child')
  34. .attr('x', -bbox.width / 2)
  35. .attr('y', -bbox.height / 2)
  36. .attr('r', r)
  37. node.intersect = function (point) {
  38. return intersectCircle(node, r, point)
  39. }
  40. return shapeSvg
  41. }
  42. // Circumscribe an ellipse for the bounding box with a diamond shape. I derived
  43. // the function to calculate the diamond shape from:
  44. // http://mathforum.org/kb/message.jspa?messageID=3750236
  45. function diamond (parent, bbox, node) {
  46. const w = (bbox.width * Math.SQRT2) / 2
  47. const h = (bbox.height * Math.SQRT2) / 2
  48. const points = [
  49. { x: 0, y: -h },
  50. { x: -w, y: 0 },
  51. { x: 0, y: h },
  52. { x: w, y: 0 }
  53. ]
  54. const shapeSvg = parent.insert('polygon', ':first-child')
  55. .attr('points', points.map(function (p) { return p.x + ',' + p.y }).join(' '))
  56. node.intersect = function (p) {
  57. return intersectPolygon(node, points, p)
  58. }
  59. return shapeSvg
  60. }
  61. export default {
  62. rect,
  63. ellipse,
  64. circle,
  65. diamond
  66. }