FamilyRelationGraph.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. <template>
  2. <!-- 全 Canvas 关系图谱 - Force-directed 物理布局 -->
  3. <view class="family-graph-wrapper" v-if="simNodes && simNodes.length >= 1">
  4. <canvas
  5. class="family-graph-canvas"
  6. canvas-id="forceGraphCanvas"
  7. id="forceGraphCanvas"
  8. type="2d"
  9. :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
  10. @touchstart="onTouchStart"
  11. @touchmove="onTouchMove"
  12. @touchend="onTouchEnd" />
  13. </view>
  14. <!-- 空状态 -->
  15. <view class="family-graph-empty" v-else-if="members && members.length === 0">
  16. <text class="empty-text">暂无家庭成员</text>
  17. </view>
  18. </template>
  19. <script>
  20. /**
  21. * FamilyRelationGraph - 全 Canvas force-directed 家庭关系图
  22. *
  23. * 物理引擎: 手动实现的 force-directed 布局
  24. * - 节点间斥力 (repulsion)
  25. * - 边弹簧引力 (spring attraction)
  26. * - 中心引力 (centering)
  27. * - 阻尼 (damping)
  28. *
  29. * 渲染: 全 Canvas 绘制 (节点 + 连线)
  30. * 交互: 节点拖拽 + 点击检测
  31. */
  32. export default {
  33. name: 'FamilyRelationGraph',
  34. props: {
  35. dimensionCode: {
  36. type: String,
  37. required: true,
  38. validator: function(val) {
  39. return ['body', 'mind', 'action', 'home', 'wisdom'].indexOf(val) !== -1
  40. }
  41. },
  42. selfId: {
  43. type: [Number, String],
  44. default: null
  45. },
  46. members: {
  47. type: Array,
  48. default: function() { return [] }
  49. },
  50. energyMap: {
  51. type: Object,
  52. default: function() { return {} }
  53. },
  54. intimacyMap: {
  55. type: Object,
  56. default: function() { return {} }
  57. },
  58. interactive: {
  59. type: Boolean,
  60. default: true
  61. },
  62. compatibilityMap: {
  63. type: Object,
  64. default: function() { return {} }
  65. }
  66. },
  67. data: function() {
  68. return {
  69. canvasWidth: 340,
  70. canvasHeight: 280,
  71. dpr: 1,
  72. // 物理模拟节点
  73. simNodes: [],
  74. // 物理参数
  75. physics: {
  76. repulsion: 800,
  77. springLength: 120,
  78. springStrength: 0.04,
  79. centering: 0.03,
  80. damping: 0.88,
  81. maxSpeed: 12,
  82. minDistance: 30
  83. },
  84. // 拖拽状态
  85. dragging: null,
  86. dragStartPos: null,
  87. // 动画
  88. animFrameId: null,
  89. isSimulating: false,
  90. // 主题色
  91. themeColors: {
  92. body: '#8D6E63',
  93. mind: '#FF6B35',
  94. action: '#4CAF50',
  95. home: '#5B9BD5',
  96. wisdom: '#FFD700'
  97. }
  98. }
  99. },
  100. computed: {
  101. themeColor: function() {
  102. return this.themeColors[this.dimensionCode] || '#8D6E63'
  103. },
  104. // 将 members 转换为 simNodes
  105. nodeData: function() {
  106. var self = this
  107. if (!this.members || this.members.length === 0) return []
  108. var centerX = this.canvasWidth / 2
  109. var centerY = this.canvasHeight / 2
  110. return this.members.map(function(m, idx) {
  111. var fid = m.memberId || m.id
  112. var energy = self.getEnergy(fid)
  113. var radius = 24 + (Math.max(0, Math.min(100, energy)) / 100) * 16
  114. var nick = m.nickname || m.name || '成员'
  115. if (nick === '用户') nick = '成员'
  116. var isSelf = (fid == self.selfId)
  117. var displayName = nick.charAt(0)
  118. // 圆形布局初始位置
  119. var angle = (2 * Math.PI * idx) / Math.max(1, self.members.length)
  120. var r = Math.min(self.canvasWidth, self.canvasHeight) * 0.32
  121. var initX = centerX + r * Math.cos(angle)
  122. var initY = centerY + r * Math.sin(angle)
  123. return {
  124. id: fid,
  125. nickname: nick,
  126. displayName: displayName,
  127. isSelf: isSelf,
  128. memberType: m.memberType || 'child',
  129. radius: radius,
  130. x: initX,
  131. y: initY,
  132. vx: 0,
  133. vy: 0,
  134. fx: 0,
  135. fy: 0
  136. }
  137. })
  138. },
  139. // 构建边 (self 连接到其他所有成员)
  140. edges: function() {
  141. var self = this
  142. var selfNode = this.nodeData.find(function(n) { return n.isSelf })
  143. if (!selfNode) return []
  144. var result = []
  145. this.nodeData.forEach(function(n) {
  146. if (n.id !== selfNode.id) {
  147. var pairKey = selfNode.id < n.id
  148. ? selfNode.id + '-' + n.id
  149. : n.id + '-' + selfNode.id
  150. var comp = self.compatibilityMap[pairKey]
  151. var trust = self.getIntimacy(n.id, 'trust')
  152. var comm = self.getIntimacy(n.id, 'communication')
  153. var closeness = self.getIntimacy(n.id, 'closeness')
  154. result.push({
  155. source: selfNode,
  156. target: n,
  157. trust: trust,
  158. communication: comm,
  159. closeness: closeness,
  160. compatibility: comp && comp.overallScore !== undefined ? comp.overallScore : null
  161. })
  162. }
  163. })
  164. return result
  165. }
  166. },
  167. watch: {
  168. members: function() {
  169. this.resetSimulation()
  170. },
  171. canvasWidth: function() {
  172. this.resetSimulation()
  173. },
  174. canvasHeight: function() {
  175. this.resetSimulation()
  176. }
  177. },
  178. mounted: function() {
  179. var self = this
  180. this.dpr = uni.getSystemInfoSync().pixelRatio || 1
  181. this.$nextTick(function() {
  182. self.updateCanvasSize()
  183. self.$nextTick(function() {
  184. self.initSimulation()
  185. })
  186. })
  187. },
  188. beforeDestroy: function() {
  189. this.stopSimulation()
  190. },
  191. methods: {
  192. // ===== 物理引擎 =====
  193. resetSimulation: function() {
  194. this.stopSimulation()
  195. var centerX = this.canvasWidth / 2
  196. var centerY = this.canvasHeight / 2
  197. var self = this
  198. this.nodeData.forEach(function(n, idx) {
  199. var angle = (2 * Math.PI * idx) / Math.max(1, self.nodeData.length)
  200. var r = Math.min(self.canvasWidth, self.canvasHeight) * 0.32
  201. n.x = centerX + r * Math.cos(angle)
  202. n.y = centerY + r * Math.sin(angle)
  203. n.vx = 0
  204. n.vy = 0
  205. n.fx = 0
  206. n.fy = 0
  207. })
  208. this.startSimulation()
  209. },
  210. initSimulation: function() {
  211. if (!this.nodeData || this.nodeData.length === 0) return
  212. // 复制到 simNodes
  213. this.simNodes = this.nodeData.slice()
  214. this.startSimulation()
  215. },
  216. startSimulation: function() {
  217. if (this.isSimulating) return
  218. this.isSimulating = true
  219. this.simulationTick()
  220. },
  221. stopSimulation: function() {
  222. this.isSimulating = false
  223. if (this.animFrameId) {
  224. cancelAnimationFrame(this.animFrameId)
  225. this.animFrameId = null
  226. }
  227. },
  228. simulationTick: function() {
  229. if (!this.isSimulating) return
  230. var self = this
  231. var nodes = this.simNodes
  232. var p = this.physics
  233. // 1. 清零力
  234. for (var i = 0; i < nodes.length; i++) {
  235. nodes[i].fx = 0
  236. nodes[i].fy = 0
  237. }
  238. // 2. 斥力
  239. for (var a = 0; a < nodes.length; a++) {
  240. for (var b = a + 1; b < nodes.length; b++) {
  241. var dx = nodes[b].x - nodes[a].x
  242. var dy = nodes[b].y - nodes[a].y
  243. var distSq = dx * dx + dy * dy
  244. var dist = Math.sqrt(distSq) || 0.1
  245. var force = p.repulsion / distSq
  246. var fx = (dx / dist) * force
  247. var fy = (dy / dist) * force
  248. nodes[a].fx -= fx
  249. nodes[a].fy -= fy
  250. nodes[b].fx += fx
  251. nodes[b].fy += fy
  252. }
  253. }
  254. // 3. 弹簧引力
  255. for (var e = 0; e < this.edges.length; e++) {
  256. var edge = this.edges[e]
  257. var s = edge.source
  258. var t = edge.target
  259. var dx = t.x - s.x
  260. var dy = t.y - s.y
  261. var dist = Math.sqrt(dx * dx + dy * dy) || 0.1
  262. var displacement = dist - p.springLength
  263. var force = p.springStrength * displacement
  264. var fx = (dx / dist) * force
  265. var fy = (dy / dist) * force
  266. s.fx += fx
  267. s.fy += fy
  268. t.fx -= fx
  269. t.fy -= fy
  270. }
  271. // 4. 中心引力
  272. var cx = this.canvasWidth / 2
  273. var cy = this.canvasHeight / 2
  274. for (var n = 0; n < nodes.length; n++) {
  275. nodes[n].fx += (cx - nodes[n].x) * p.centering
  276. nodes[n].fy += (cy - nodes[n].y) * p.centering
  277. }
  278. // 5. 更新速度 + 位置
  279. for (var i = 0; i < nodes.length; i++) {
  280. var node = nodes[i]
  281. node.vx += node.fx
  282. node.vy += node.fy
  283. node.vx *= p.damping
  284. node.vy *= p.damping
  285. var speed = Math.sqrt(node.vx * node.vx + node.vy * node.vy)
  286. if (speed > p.maxSpeed) {
  287. node.vx = (node.vx / speed) * p.maxSpeed
  288. node.vy = (node.vy / speed) * p.maxSpeed
  289. }
  290. node.x += node.vx
  291. node.y += node.vy
  292. // 边界
  293. var r = node.radius + 4
  294. if (node.x < r) { node.x = r; node.vx *= -0.5 }
  295. if (node.x > this.canvasWidth - r) { node.x = this.canvasWidth - r; node.vx *= -0.5 }
  296. if (node.y < r) { node.y = r; node.vy *= -0.5 }
  297. if (node.y > this.canvasHeight - r) { node.y = this.canvasHeight - r; node.vy *= -0.5 }
  298. }
  299. // 6. 渲染
  300. this.render()
  301. // 7. 下一帧
  302. this.animFrameId = requestAnimationFrame(function() {
  303. self.simulationTick()
  304. })
  305. },
  306. // ===== 渲染 =====
  307. render: function() {
  308. var self = this
  309. var query = uni.createSelectorQuery().in(this)
  310. query.select('#forceGraphCanvas')
  311. .fields({ node: true, size: true })
  312. .exec(function(res) {
  313. if (!res || !res[0] || !res[0].node) {
  314. self.renderLegacy()
  315. return
  316. }
  317. var canvas = res[0].node
  318. var ctx = canvas.getContext('2d')
  319. canvas.width = self.canvasWidth * self.dpr
  320. canvas.height = self.canvasHeight * self.dpr
  321. ctx.scale(self.dpr, self.dpr)
  322. ctx.clearRect(0, 0, self.canvasWidth, self.canvasHeight)
  323. self.drawEdges(ctx)
  324. self.drawNodes(ctx)
  325. })
  326. },
  327. drawEdges: function(ctx) {
  328. var edges = this.edges
  329. for (var i = 0; i < edges.length; i++) {
  330. var edge = edges[i]
  331. var s = edge.source
  332. var t = edge.target
  333. var trust = edge.trust || 75
  334. var comm = edge.communication || 50
  335. var hue = 120 * trust / 100
  336. ctx.strokeStyle = 'hsla(' + hue + ', 75%, 45%, 0.6)'
  337. ctx.lineWidth = 1 + (comm / 100) * 4
  338. ctx.beginPath()
  339. ctx.moveTo(s.x, s.y)
  340. ctx.lineTo(t.x, t.y)
  341. ctx.stroke()
  342. }
  343. },
  344. drawNodes: function(ctx) {
  345. var nodes = this.simNodes
  346. for (var i = 0; i < nodes.length; i++) {
  347. var node = nodes[i]
  348. var r = node.radius
  349. ctx.beginPath()
  350. ctx.arc(node.x, node.y, r, 0, 2 * Math.PI)
  351. if (node.isSelf) {
  352. ctx.fillStyle = '#FFFFFF'
  353. ctx.fill()
  354. ctx.strokeStyle = this.themeColor
  355. ctx.lineWidth = 3
  356. ctx.stroke()
  357. } else {
  358. ctx.fillStyle = this.themeColor + '22'
  359. ctx.fill()
  360. }
  361. ctx.fillStyle = node.isSelf ? this.themeColor : '#4A5568'
  362. ctx.font = 'bold ' + (r * 0.9) + 'px sans-serif'
  363. ctx.textAlign = 'center'
  364. ctx.textBaseline = 'middle'
  365. ctx.fillText(node.displayName, node.x, node.y)
  366. ctx.fillStyle = node.isSelf ? this.themeColor : '#94A3B8'
  367. ctx.font = (r * 0.4) + 'px sans-serif'
  368. ctx.fillText(node.nickname.substring(0, 3), node.x, node.y + r + 10)
  369. }
  370. },
  371. renderLegacy: function() {
  372. var ctx = uni.createCanvasContext('forceGraphCanvas', this)
  373. var self = this
  374. ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
  375. var edges = this.edges
  376. for (var i = 0; i < edges.length; i++) {
  377. var edge = edges[i]
  378. var trust = edge.trust || 75
  379. var comm = edge.communication || 50
  380. var hue = 120 * trust / 100
  381. ctx.setStrokeStyle('hsla(' + hue + ', 75%, 45%, 0.6)')
  382. ctx.setLineWidth(1 + (comm / 100) * 4)
  383. ctx.beginPath()
  384. ctx.moveTo(edge.source.x, edge.source.y)
  385. ctx.lineTo(edge.target.x, edge.target.y)
  386. ctx.stroke()
  387. }
  388. var nodes = this.simNodes
  389. for (var j = 0; j < nodes.length; j++) {
  390. var node = nodes[j]
  391. var r = node.radius
  392. ctx.beginPath()
  393. ctx.arc(node.x, node.y, r, 0, 2 * Math.PI)
  394. if (node.isSelf) {
  395. ctx.setFillStyle('#FFFFFF')
  396. ctx.fill()
  397. ctx.setStrokeStyle(this.themeColor)
  398. ctx.setLineWidth(3)
  399. ctx.stroke()
  400. } else {
  401. ctx.setFillStyle(this.themeColor + '22')
  402. ctx.fill()
  403. }
  404. ctx.setFillStyle(node.isSelf ? this.themeColor : '#4A5568')
  405. ctx.setFont('bold ' + (r * 0.9) + 'px sans-serif')
  406. ctx.setTextAlign('center')
  407. ctx.setTextBaseline('middle')
  408. ctx.fillText(node.displayName, node.x, node.y)
  409. ctx.setFillStyle(node.isSelf ? this.themeColor : '#94A3B8')
  410. ctx.setFont((r * 0.4) + 'px sans-serif')
  411. ctx.fillText(node.nickname.substring(0, 3), node.x, node.y + r + 10)
  412. }
  413. ctx.draw()
  414. },
  415. // ===== 交互 =====
  416. getTouchNode: function(touchX, touchY) {
  417. var nodes = this.simNodes
  418. for (var i = 0; i < nodes.length; i++) {
  419. var node = nodes[i]
  420. var dx = touchX - node.x
  421. var dy = touchY - node.y
  422. var dist = Math.sqrt(dx * dx + dy * dy)
  423. if (dist <= node.radius + 8) {
  424. return node
  425. }
  426. }
  427. return null
  428. },
  429. onTouchStart: function(e) {
  430. if (!this.interactive) return
  431. var touch = e.touches ? e.touches[0] : e.detail
  432. if (!touch) return
  433. var self = this
  434. var rect = {}
  435. var query = uni.createSelectorQuery().in(this)
  436. query.select('#forceGraphCanvas').boundingClientRect()
  437. query.exec(function(res) {
  438. if (res && res[0]) {
  439. rect = res[0]
  440. var x = touch.clientX - rect.left
  441. var y = touch.clientY - rect.top
  442. var node = self.getTouchNode(x, y)
  443. if (node) {
  444. self.dragging = { node: node, offsetX: x - node.x, offsetY: y - node.y }
  445. self.dragStartPos = { x: x, y: y }
  446. }
  447. }
  448. })
  449. },
  450. onTouchMove: function(e) {
  451. if (!this.dragging) return
  452. e.preventDefault && e.preventDefault()
  453. var touch = e.touches ? e.touches[0] : e.detail
  454. if (!touch) return
  455. var self = this
  456. var rect = {}
  457. var query = uni.createSelectorQuery().in(this)
  458. query.select('#forceGraphCanvas').boundingClientRect()
  459. query.exec(function(res) {
  460. if (res && res[0]) {
  461. rect = res[0]
  462. var x = touch.clientX - rect.left
  463. var y = touch.clientY - rect.top
  464. var node = self.dragging.node
  465. node.x = x - self.dragging.offsetX
  466. node.y = y - self.dragging.offsetY
  467. }
  468. })
  469. },
  470. onTouchEnd: function(e) {
  471. if (!this.dragging) return
  472. var wasDragged = this.dragStartPos && (
  473. Math.abs(this.dragging.node.x - this.dragStartPos.x) > 5 ||
  474. Math.abs(this.dragging.node.y - this.dragStartPos.y) > 5
  475. )
  476. var node = this.dragging.node
  477. if (!wasDragged && this.interactive) {
  478. this.$emit('memberTap', {
  479. memberId: node.id,
  480. memberType: node.memberType,
  481. nickname: node.nickname
  482. })
  483. }
  484. this.dragging = null
  485. this.dragStartPos = null
  486. },
  487. // ===== 工具方法 =====
  488. getEnergy: function(memberId) {
  489. var data = this.energyMap[memberId]
  490. if (!data) return 0
  491. var key = this.dimensionCode + 'Score'
  492. var val = data[key]
  493. return (typeof val !== 'undefined' && val !== null) ? val : 0
  494. },
  495. getIntimacy: function(memberId, key) {
  496. var data = this.intimacyMap[memberId]
  497. if (!data) {
  498. var defaults = { closeness: 75, communication: 50, trust: 85 }
  499. return defaults[key]
  500. }
  501. var val = data[key]
  502. return (typeof val !== 'undefined' && val !== null) ? val : 75
  503. },
  504. updateCanvasSize: function() {
  505. var self = this
  506. var query = uni.createSelectorQuery().in(this)
  507. query.select('.family-graph-wrapper').boundingClientRect(function(rect) {
  508. if (rect) {
  509. self.canvasWidth = rect.width || 340
  510. self.canvasHeight = rect.height || 280
  511. }
  512. }).exec()
  513. }
  514. }
  515. }
  516. </script>
  517. <style scoped>
  518. .family-graph-wrapper {
  519. position: relative;
  520. width: 100%;
  521. height: 280px;
  522. margin: 10rpx 0;
  523. background: #FFFFFF;
  524. border-radius: 24rpx;
  525. overflow: hidden;
  526. }
  527. .family-graph-canvas {
  528. position: absolute;
  529. top: 0;
  530. left: 0;
  531. z-index: 1;
  532. }
  533. .family-graph-empty {
  534. display: flex;
  535. align-items: center;
  536. justify-content: center;
  537. padding: 60rpx 0;
  538. background: #FFFFFF;
  539. border-radius: 24rpx;
  540. margin: 10rpx 0;
  541. }
  542. .empty-text {
  543. font-size: 28rpx;
  544. color: #94A3B8;
  545. }
  546. </style>