FamilyRelationGraph.vue 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. <template>
  2. <!-- 全 Canvas 关系图谱 - Force-directed 物理布局 -->
  3. <view class="family-graph-wrapper" v-if="members && members.length >= 1" :style="{ minHeight: canvasHeight + 'px' }">
  4. <!-- 右上角小齿轮 → 成员管理 -->
  5. <view class="gear-icon" @click="onManageTap" @tap.stop="onManageTap">
  6. <text class="gear-text">⚙</text>
  7. </view>
  8. <canvas
  9. class="family-graph-canvas"
  10. canvas-id="forceGraphCanvas"
  11. id="forceGraphCanvas"
  12. type="2d"
  13. :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
  14. @touchstart="onTouchStart"
  15. @touchmove="onTouchMove"
  16. @touchend="onTouchEnd" />
  17. <!-- ⚙ 维护页提示(触摸自身节点时显示) -->
  18. <view class="add-hint" :class="{ 'add-hint-visible': touchingSelf }" :style="addHintPosition">
  19. <text class="add-hint-text">⚙</text>
  20. </view>
  21. </view>
  22. <!-- 空状态 -->
  23. <view class="family-graph-empty" v-else-if="members && members.length === 0">
  24. <text class="empty-text">暂无家庭成员</text>
  25. </view>
  26. </template>
  27. <script>
  28. /**
  29. * FamilyRelationGraph - 全 Canvas force-directed 家庭关系图
  30. *
  31. * 物理引擎: 手动实现的 force-directed 布局
  32. * - 节点间斥力 (repulsion)
  33. * - 边弹簧引力 (spring attraction)
  34. * - 中心引力 (centering)
  35. * - 阻尼 (damping)
  36. *
  37. * 渲染: 全 Canvas 绘制 (节点 + 连线)
  38. * 交互: 节点拖拽 + 点击检测
  39. */
  40. export default {
  41. name: 'FamilyRelationGraph',
  42. props: {
  43. dimensionCode: {
  44. type: String,
  45. required: true,
  46. validator: function(val) {
  47. return ['body', 'mind', 'action', 'home', 'wisdom'].indexOf(val) !== -1
  48. }
  49. },
  50. selfId: {
  51. type: [Number, String],
  52. default: null
  53. },
  54. members: {
  55. type: Array,
  56. default: function() { return [] }
  57. },
  58. energyMap: {
  59. type: Object,
  60. default: function() { return {} }
  61. },
  62. intimacyMap: {
  63. type: Object,
  64. default: function() { return {} }
  65. },
  66. interactive: {
  67. type: Boolean,
  68. default: true
  69. },
  70. compatibilityMap: {
  71. type: Object,
  72. default: function() { return {} }
  73. }
  74. },
  75. data: function() {
  76. return {
  77. canvasWidth: 340,
  78. canvasHeight: 280,
  79. dpr: 1,
  80. // 物理参数
  81. physics: {
  82. repulsion: 800, // 节点间斥力强度
  83. springLength: 120, // 弹簧自然长度
  84. springStrength: 0.04, // 弹簧劲度系数
  85. centering: 0.03, // 中心引力
  86. damping: 0.88, // 速度阻尼
  87. maxSpeed: 12, // 最大速度
  88. minDistance: 30 // 最小节点距离
  89. },
  90. // 拖拽状态
  91. dragging: null, // { nodeIndex, offsetX, offsetY }
  92. dragStartPos: null, // 用于判断是否真的拖拽了
  93. // 触摸/悬停状态(显示 ⚙ 提示)
  94. touchingSelf: false,
  95. hoveringSelf: false,
  96. // 是否 PC 环境(h5 编译)
  97. isPC: false,
  98. // 动画
  99. animFrameId: null,
  100. isSimulating: false,
  101. // 动能收敛检测(布局收敛后自动停止,避免永续占用主线程)
  102. stillFrames: 0, // 连续低动能帧计数
  103. energyThreshold: 2, // 总动能阈值(各节点速度平方和)
  104. stillFrameLimit: 30, // 连续 30 帧低动能(约 0.5s)→ 停止
  105. // 主题色
  106. themeColors: {
  107. body: '#8D6E63',
  108. mind: '#FF6B35',
  109. action: '#4CAF50',
  110. home: '#5B9BD5',
  111. wisdom: '#FFD700'
  112. }
  113. }
  114. },
  115. computed: {
  116. themeColor: function() {
  117. return this.themeColors[this.dimensionCode] || '#8D6E63'
  118. },
  119. // ⚙ 提示位置(跟随自身节点偏移)
  120. addHintPosition: function() {
  121. var selfNode = this.nodeData.find(function(n) { return n.isSelf })
  122. if (!selfNode) return {}
  123. return {
  124. left: (selfNode.x + selfNode.radius * 0.7) + 'px',
  125. top: (selfNode.y - selfNode.radius * 0.5) + 'px'
  126. }
  127. },
  128. // 将 members 转换为 simNodes
  129. nodeData: function() {
  130. var self = this
  131. if (!this.members || this.members.length === 0) return []
  132. var selfMemberId = null
  133. var centerX = this.canvasWidth / 2
  134. var centerY = this.canvasHeight / 2
  135. return this.members.map(function(m, idx) {
  136. var fid = m.memberId || m.id
  137. if (fid == self.selfId) selfMemberId = fid
  138. var energy = self.getEnergy(fid)
  139. var radius = 24 + (Math.max(0, Math.min(100, energy)) / 100) * 16 // 24-40rpx
  140. var nick = m.nickname || m.name || '成员'
  141. if (nick === '用户') nick = '成员'
  142. var isSelf = (fid == self.selfId)
  143. var displayName = nick.charAt(0)
  144. // 圆形布局初始位置(避免初始重叠)
  145. var angle = (2 * Math.PI * idx) / self.members.length
  146. var r = Math.min(self.canvasWidth, self.canvasHeight) * 0.32
  147. var initX = centerX + r * Math.cos(angle)
  148. var initY = centerY + r * Math.sin(angle)
  149. return {
  150. id: fid,
  151. nickname: nick,
  152. displayName: displayName,
  153. isSelf: isSelf,
  154. memberType: m.memberType || 'child',
  155. effectiveRole: m.effectiveRole || m.relativeLabel || '',
  156. gender: m.gender || '',
  157. relativeLabel: m.relativeLabel || '',
  158. radius: radius,
  159. x: initX,
  160. y: initY,
  161. vx: 0,
  162. vy: 0,
  163. fx: 0,
  164. fy: 0
  165. }
  166. })
  167. },
  168. // 构建边 (self 连接到其他所有成员)
  169. edges: function() {
  170. var self = this
  171. var selfNode = this.nodeData.find(function(n) { return n.isSelf })
  172. if (!selfNode) return []
  173. var result = []
  174. this.nodeData.forEach(function(n) {
  175. if (n.id !== selfNode.id) {
  176. // 获取亲密度
  177. var pairKey = selfNode.id < n.id
  178. ? selfNode.id + '-' + n.id
  179. : n.id + '-' + selfNode.id
  180. var comp = self.compatibilityMap[pairKey]
  181. var trust = self.getIntimacy(n.id, 'trust')
  182. var comm = self.getIntimacy(n.id, 'communication')
  183. var closeness = self.getIntimacy(n.id, 'closeness')
  184. result.push({
  185. source: selfNode,
  186. target: n,
  187. // 边权重用于可视化
  188. trust: trust,
  189. communication: comm,
  190. closeness: closeness,
  191. compatibility: comp && comp.overallScore !== undefined ? comp.overallScore : null
  192. })
  193. }
  194. })
  195. return result
  196. }
  197. },
  198. watch: {
  199. members: function() {
  200. this.resetSimulation()
  201. },
  202. canvasWidth: function() {
  203. this.resetSimulation()
  204. },
  205. canvasHeight: function() {
  206. this.resetSimulation()
  207. }
  208. },
  209. mounted: function() {
  210. this._destroyed = false
  211. var self = this
  212. try {
  213. this.dpr = uni.getWindowInfo().pixelRatio || 1
  214. } catch (e) {
  215. this.dpr = 1
  216. }
  217. this.$nextTick(function() {
  218. if (self._destroyed) return
  219. self.updateCanvasSize()
  220. self.$nextTick(function() {
  221. if (!self._destroyed) {
  222. self.initSimulation()
  223. }
  224. })
  225. })
  226. },
  227. beforeDestroy: function() {
  228. this._destroyed = true
  229. this.stopSimulation()
  230. },
  231. methods: {
  232. // ===== 物理引擎 =====
  233. resetSimulation: function() {
  234. this.stopSimulation()
  235. // 重新初始化节点位置
  236. var centerX = this.canvasWidth / 2
  237. var centerY = this.canvasHeight / 2
  238. var self = this
  239. this.nodeData.forEach(function(n, idx) {
  240. var angle = (2 * Math.PI * idx) / self.nodeData.length
  241. var r = Math.min(self.canvasWidth, self.canvasHeight) * 0.32
  242. n.x = centerX + r * Math.cos(angle)
  243. n.y = centerY + r * Math.sin(angle)
  244. n.vx = 0
  245. n.vy = 0
  246. n.fx = 0
  247. n.fy = 0
  248. })
  249. this.startSimulation()
  250. },
  251. initSimulation: function() {
  252. if (!this.nodeData || this.nodeData.length === 0) return
  253. this.startSimulation()
  254. },
  255. // hex → rgba(小程序不支持 8 位 hex 颜色 #RRGGBBAA)
  256. hexToRgba: function(hex, alpha) {
  257. var r = parseInt(hex.slice(1, 3), 16)
  258. var g = parseInt(hex.slice(3, 5), 16)
  259. var b = parseInt(hex.slice(5, 7), 16)
  260. return 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')'
  261. },
  262. startSimulation: function() {
  263. if (this.isSimulating) return
  264. this.isSimulating = true
  265. this.stillFrames = 0
  266. this.simulationTick()
  267. },
  268. stopSimulation: function() {
  269. this.isSimulating = false
  270. if (this.animFrameId) {
  271. clearTimeout(this.animFrameId)
  272. this.animFrameId = null
  273. }
  274. },
  275. simulationTick: function() {
  276. if (!this.isSimulating) return
  277. if (this._destroyed) {
  278. this.isSimulating = false
  279. return
  280. }
  281. var self = this
  282. var nodes = this.nodeData
  283. var edges = this.edges
  284. var p = this.physics
  285. // 1. 清零力
  286. for (var i = 0; i < nodes.length; i++) {
  287. if (!nodes[i].fixed) {
  288. nodes[i].fx = 0
  289. nodes[i].fy = 0
  290. }
  291. }
  292. // 2. 斥力 (所有节点对之间)
  293. for (var a = 0; a < nodes.length; a++) {
  294. for (var b = a + 1; b < nodes.length; b++) {
  295. var dx = nodes[b].x - nodes[a].x
  296. var dy = nodes[b].y - nodes[a].y
  297. var distSq = dx * dx + dy * dy
  298. var dist = Math.sqrt(distSq) || 0.1
  299. // F = repulsion / dist^2
  300. var force = p.repulsion / distSq
  301. var fx = (dx / dist) * force
  302. var fy = (dy / dist) * force
  303. if (!nodes[a].fixed) {
  304. nodes[a].fx -= fx
  305. nodes[a].fy -= fy
  306. }
  307. if (!nodes[b].fixed) {
  308. nodes[b].fx += fx
  309. nodes[b].fy += fy
  310. }
  311. }
  312. }
  313. // 3. 弹簧引力 (边)
  314. for (var e = 0; e < edges.length; e++) {
  315. var edge = edges[e]
  316. var s = edge.source
  317. var t = edge.target
  318. var dx = t.x - s.x
  319. var dy = t.y - s.y
  320. var dist = Math.sqrt(dx * dx + dy * dy) || 0.1
  321. var displacement = dist - p.springLength
  322. var force = p.springStrength * displacement
  323. var fx = (dx / dist) * force
  324. var fy = (dy / dist) * force
  325. if (!s.fixed) {
  326. s.fx += fx
  327. s.fy += fy
  328. }
  329. if (!t.fixed) {
  330. t.fx -= fx
  331. t.fy -= fy
  332. }
  333. }
  334. // 4. 中心引力
  335. var cx = this.canvasWidth / 2
  336. var cy = this.canvasHeight / 2
  337. for (var n = 0; n < nodes.length; n++) {
  338. if (!nodes[n].fixed) {
  339. nodes[n].fx += (cx - nodes[n].x) * p.centering
  340. nodes[n].fy += (cy - nodes[n].y) * p.centering
  341. }
  342. }
  343. // 5. 更新速度 + 位置
  344. var totalEnergy = 0
  345. for (var i = 0; i < nodes.length; i++) {
  346. var node = nodes[i]
  347. if (node.fixed) continue
  348. node.vx += node.fx
  349. node.vy += node.fy
  350. // 阻尼
  351. node.vx *= p.damping
  352. node.vy *= p.damping
  353. // 限速
  354. var speed = Math.sqrt(node.vx * node.vx + node.vy * node.vy)
  355. if (speed > p.maxSpeed) {
  356. node.vx = (node.vx / speed) * p.maxSpeed
  357. node.vy = (node.vy / speed) * p.maxSpeed
  358. }
  359. // 最小距离约束
  360. for (var j = 0; j < nodes.length; j++) {
  361. if (i === j) continue
  362. var other = nodes[j]
  363. var dx = other.x - node.x
  364. var dy = other.y - node.y
  365. var dist = Math.sqrt(dx * dx + dy * dy) || 0.1
  366. var minDist = node.radius + other.radius
  367. if (dist < minDist && dist > 0) {
  368. var overlap = (minDist - dist) / 2
  369. var nx = dx / dist
  370. var ny = dy / dist
  371. node.x -= nx * overlap
  372. node.y -= ny * overlap
  373. other.x += nx * overlap
  374. other.y += ny * overlap
  375. }
  376. }
  377. node.x += node.vx
  378. node.y += node.vy
  379. // 累计动能(用于收敛检测)
  380. totalEnergy += node.vx * node.vx + node.vy * node.vy
  381. // 边界约束
  382. var r = node.radius + 4
  383. if (node.x < r) { node.x = r; node.vx *= -0.5 }
  384. if (node.x > this.canvasWidth - r) { node.x = this.canvasWidth - r; node.vx *= -0.5 }
  385. if (node.y < r) { node.y = r; node.vy *= -0.5 }
  386. if (node.y > this.canvasHeight - r) { node.y = this.canvasHeight - r; node.vy *= -0.5 }
  387. }
  388. // 5.5 动能收敛检测:布局基本稳定后自动停止,避免永续占用主线程(模拟器会判定长时间无响应)
  389. if (totalEnergy < this.energyThreshold) {
  390. this.stillFrames++
  391. if (this.stillFrames >= this.stillFrameLimit) {
  392. this.stopSimulation()
  393. return
  394. }
  395. } else {
  396. this.stillFrames = 0
  397. }
  398. // 6. 渲染
  399. this.render()
  400. // 7. 下一帧(小程序无 requestAnimationFrame,用 setTimeout 降级)
  401. this.animFrameId = setTimeout(function() {
  402. self.simulationTick()
  403. }, 16)
  404. },
  405. // ===== 渲染 =====
  406. render: function() {
  407. var self = this
  408. var query = uni.createSelectorQuery().in(this)
  409. query.select('#forceGraphCanvas')
  410. .fields({ node: true, size: true })
  411. .exec(function(res) {
  412. if (!res || !res[0] || !res[0].node) {
  413. self.renderLegacy()
  414. return
  415. }
  416. var canvas = res[0].node
  417. var ctx = canvas.getContext('2d')
  418. canvas.width = self.canvasWidth * self.dpr
  419. canvas.height = self.canvasHeight * self.dpr
  420. ctx.scale(self.dpr, self.dpr)
  421. // 清空
  422. ctx.clearRect(0, 0, self.canvasWidth, self.canvasHeight)
  423. // 画边
  424. self.drawEdges(ctx)
  425. // 画节点
  426. self.drawNodes(ctx)
  427. })
  428. },
  429. drawEdges: function(ctx) {
  430. var edges = this.edges
  431. for (var i = 0; i < edges.length; i++) {
  432. var edge = edges[i]
  433. var s = edge.source
  434. var t = edge.target
  435. var intimacy = edge.closeness // 亲密度 → 连线粗细
  436. var trust = edge.trust // 信任度 → 连线颜色(低红高绿)
  437. var comm = edge.communication // 沟通度 → 线形(越多越实)
  438. var hasData = intimacy !== null || trust !== null || comm !== null
  439. if (!hasData) {
  440. // 无数据: 默认黑色实线 1px
  441. ctx.lineWidth = 1
  442. ctx.setLineDash([])
  443. ctx.strokeStyle = '#000000'
  444. } else {
  445. // 连线粗细 = 亲密度 (1-6px, 越高越粗)
  446. var intVal = intimacy != null ? intimacy : 50
  447. ctx.lineWidth = 1 + (intVal / 100) * 5
  448. // 连线颜色 = 信任度 (低=红, 高=绿)
  449. var trustVal = trust != null ? trust : 50
  450. var green = Math.round((trustVal / 100) * 180)
  451. var red = Math.round((1 - trustVal / 100) * 200 + 55)
  452. ctx.strokeStyle = 'rgba(' + red + ',' + green + ', 60, 0.7)'
  453. // 虚线密度 = 沟通度 (越多越实)
  454. var commVal = comm != null ? comm : 50
  455. if (commVal >= 90) {
  456. ctx.setLineDash([])
  457. } else if (commVal >= 70) {
  458. ctx.setLineDash([8, 3])
  459. } else if (commVal >= 50) {
  460. ctx.setLineDash([5, 5])
  461. } else if (commVal >= 30) {
  462. ctx.setLineDash([3, 8])
  463. } else {
  464. ctx.setLineDash([2, 12])
  465. }
  466. }
  467. ctx.beginPath()
  468. ctx.moveTo(s.x, s.y)
  469. ctx.lineTo(t.x, t.y)
  470. ctx.stroke()
  471. }
  472. },
  473. // ===== 身份 → 形状映射 =====
  474. getNodeShapeType: function(node) {
  475. var role = node.effectiveRole || node.relativeLabel || ''
  476. var type = node.memberType || ''
  477. // 长辈 (爷爷/奶奶/外公/外婆)
  478. if (role.indexOf('爷爷') !== -1 || role.indexOf('奶奶') !== -1 ||
  479. role.indexOf('外公') !== -1 || role.indexOf('外婆') !== -1 ||
  480. role.indexOf('祖父') !== -1 || role.indexOf('祖母') !== -1) {
  481. return 'diamond'
  482. }
  483. // 父亲/男性家长
  484. if (role.indexOf('爸爸') !== -1 || role.indexOf('父亲') !== -1 ||
  485. role.indexOf('爸') !== -1 || role.indexOf('爹') !== -1) {
  486. return 'roundedRect'
  487. }
  488. // 母亲/女性家长
  489. if (role.indexOf('妈妈') !== -1 || role.indexOf('母亲') !== -1 ||
  490. role.indexOf('妈') !== -1 || role.indexOf('娘') !== -1) {
  491. return 'circle'
  492. }
  493. // 通用 parent → 根据性别区分
  494. if (type === 'parent') {
  495. return node.gender === 'male' ? 'roundedRect' : 'circle'
  496. }
  497. // child → 圆形
  498. if (type === 'child') {
  499. return 'childCircle'
  500. }
  501. return 'circle'
  502. },
  503. // 绘制圆角矩形
  504. drawRoundedRectNode: function(ctx, x, y, r) {
  505. var w = r * 1.8
  506. var h = r * 1.8
  507. var cr = r * 0.3
  508. ctx.beginPath()
  509. ctx.moveTo(x - w/2 + cr, y - h/2)
  510. ctx.lineTo(x + w/2 - cr, y - h/2)
  511. ctx.arcTo(x + w/2, y - h/2, x + w/2, y - h/2 + cr, cr)
  512. ctx.lineTo(x + w/2, y + h/2 - cr)
  513. ctx.arcTo(x + w/2, y + h/2, x + w/2 - cr, y + h/2, cr)
  514. ctx.lineTo(x - w/2 + cr, y + h/2)
  515. ctx.arcTo(x - w/2, y + h/2, x - w/2, y + h/2 - cr, cr)
  516. ctx.lineTo(x - w/2, y - h/2 + cr)
  517. ctx.arcTo(x - w/2, y - h/2, x - w/2 + cr, y - h/2, cr)
  518. ctx.closePath()
  519. },
  520. // 绘制菱形
  521. drawDiamondNode: function(ctx, x, y, r) {
  522. ctx.beginPath()
  523. ctx.moveTo(x, y - r * 1.2)
  524. ctx.lineTo(x + r * 1.2, y)
  525. ctx.lineTo(x, y + r * 1.2)
  526. ctx.lineTo(x - r * 1.2, y)
  527. ctx.closePath()
  528. },
  529. drawNodes: function(ctx) {
  530. var nodes = this.nodeData
  531. for (var i = 0; i < nodes.length; i++) {
  532. var node = nodes[i]
  533. var r = node.radius
  534. var shapeType = this.getNodeShapeType(node)
  535. // 按身份绘制不同形状
  536. if (shapeType === 'roundedRect') {
  537. this.drawRoundedRectNode(ctx, node.x, node.y, r)
  538. } else if (shapeType === 'diamond') {
  539. this.drawDiamondNode(ctx, node.x, node.y, r)
  540. } else {
  541. // 默认圆形 (母亲/女性家长/孩子)
  542. ctx.beginPath()
  543. ctx.arc(node.x, node.y, r, 0, 2 * Math.PI)
  544. }
  545. // 填充 + 描边
  546. if (node.isSelf) {
  547. ctx.fillStyle = '#FFFFFF'
  548. ctx.fill()
  549. ctx.strokeStyle = this.themeColor
  550. ctx.lineWidth = 3
  551. ctx.stroke()
  552. } else {
  553. ctx.fillStyle = this.hexToRgba(this.themeColor, 0.13)
  554. ctx.fill()
  555. }
  556. // 第一字符 (昵称首字)
  557. ctx.fillStyle = node.isSelf ? this.themeColor : '#4A5568'
  558. ctx.font = 'bold ' + (r * 0.9) + 'px sans-serif'
  559. ctx.textAlign = 'center'
  560. ctx.textBaseline = 'middle'
  561. ctx.fillText(node.displayName, node.x, node.y)
  562. // 昵称
  563. ctx.fillStyle = node.isSelf ? this.themeColor : '#94A3B8'
  564. ctx.font = (r * 0.4) + 'px sans-serif'
  565. ctx.fillText(node.nickname.substring(0, 3), node.x, node.y + r + 10)
  566. }
  567. },
  568. // WeChat mini-program compatible fallback renderer.
  569. // Note: uni-app legacy canvas uses setFontSize(size), not setFont().
  570. renderLegacy: function() {
  571. if (this._destroyed) return
  572. try {
  573. var ctx = uni.createCanvasContext('forceGraphCanvas', this)
  574. var self = this
  575. ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
  576. var edges = this.edges
  577. for (var i = 0; i < edges.length; i++) {
  578. var edge = edges[i]
  579. var intimacy = edge.closeness // 亲密度 → 连线粗细
  580. var trust = edge.trust // 信任度 → 连线颜色(低红高绿)
  581. var comm = edge.communication // 沟通度 → 线形(越多越实)
  582. var hasData = intimacy !== null || trust !== null || comm !== null
  583. if (!hasData) {
  584. // 无数据: 默认黑色实线 1px
  585. ctx.setLineWidth(1)
  586. ctx.setLineDash([])
  587. ctx.setStrokeStyle('#000000')
  588. } else {
  589. // 连线粗细 = 亲密度
  590. var intVal = intimacy != null ? intimacy : 50
  591. ctx.setLineWidth(1 + (intVal / 100) * 5)
  592. // 连线颜色 = 信任度 (低=红, 高=绿)
  593. var trustVal = trust != null ? trust : 50
  594. var green = Math.round((trustVal / 100) * 180)
  595. var red = Math.round((1 - trustVal / 100) * 200 + 55)
  596. ctx.setStrokeStyle('rgba(' + red + ',' + green + ', 60, 0.7)')
  597. // 虚线密度 = 沟通度 (越多越实)
  598. var commVal = comm != null ? comm : 50
  599. if (commVal >= 90) {
  600. ctx.setLineDash([])
  601. } else if (commVal >= 70) {
  602. ctx.setLineDash([8, 3])
  603. } else if (commVal >= 50) {
  604. ctx.setLineDash([5, 5])
  605. } else if (commVal >= 30) {
  606. ctx.setLineDash([3, 8])
  607. } else {
  608. ctx.setLineDash([2, 12])
  609. }
  610. }
  611. ctx.beginPath()
  612. ctx.moveTo(edge.source.x, edge.source.y)
  613. ctx.lineTo(edge.target.x, edge.target.y)
  614. ctx.stroke()
  615. }
  616. var nodes = this.nodeData
  617. for (var j = 0; j < nodes.length; j++) {
  618. var node = nodes[j]
  619. var r = node.radius
  620. var shapeType = this.getNodeShapeType(node)
  621. // legacy API 的形状绘制
  622. if (shapeType === 'roundedRect') {
  623. var w = r * 1.8
  624. var h = r * 1.8
  625. var cr = r * 0.3
  626. ctx.beginPath()
  627. ctx.moveTo(node.x - w/2 + cr, node.y - h/2)
  628. ctx.lineTo(node.x + w/2 - cr, node.y - h/2)
  629. ctx.arcTo(node.x + w/2, node.y - h/2, node.x + w/2, node.y - h/2 + cr, cr)
  630. ctx.lineTo(node.x + w/2, node.y + h/2 - cr)
  631. ctx.arcTo(node.x + w/2, node.y + h/2, node.x + w/2 - cr, node.y + h/2, cr)
  632. ctx.lineTo(node.x - w/2 + cr, node.y + h/2)
  633. ctx.arcTo(node.x - w/2, node.y + h/2, node.x - w/2, node.y + h/2 - cr, cr)
  634. ctx.lineTo(node.x - w/2, node.y - h/2 + cr)
  635. ctx.arcTo(node.x - w/2, node.y - h/2, node.x - w/2 + cr, node.y - h/2, cr)
  636. ctx.closePath()
  637. } else if (shapeType === 'diamond') {
  638. ctx.beginPath()
  639. ctx.moveTo(node.x, node.y - r * 1.2)
  640. ctx.lineTo(node.x + r * 1.2, node.y)
  641. ctx.lineTo(node.x, node.y + r * 1.2)
  642. ctx.lineTo(node.x - r * 1.2, node.y)
  643. ctx.closePath()
  644. } else {
  645. ctx.beginPath()
  646. ctx.arc(node.x, node.y, r, 0, 2 * Math.PI)
  647. }
  648. if (node.isSelf) {
  649. ctx.setFillStyle('#FFFFFF')
  650. ctx.fill()
  651. ctx.setStrokeStyle(this.themeColor)
  652. ctx.setLineWidth(3)
  653. ctx.stroke()
  654. } else {
  655. ctx.setFillStyle(this.hexToRgba(this.themeColor, 0.13))
  656. ctx.fill()
  657. }
  658. ctx.setFillStyle(node.isSelf ? this.themeColor : '#4A5568')
  659. ctx.setFontSize(Math.max(10, Math.round(r * 0.9)))
  660. ctx.setTextAlign('center')
  661. ctx.setTextBaseline('middle')
  662. ctx.fillText(node.displayName, node.x, node.y)
  663. ctx.setFillStyle(node.isSelf ? this.themeColor : '#94A3B8')
  664. ctx.setFontSize(Math.max(9, Math.round(r * 0.4)))
  665. ctx.fillText((node.nickname || '').substring(0, 3), node.x, node.y + r + 10)
  666. }
  667. ctx.draw()
  668. } catch (err) {
  669. // Legacy canvas fallback must never crash page initialization.
  670. }
  671. },
  672. // ===== 交互 =====
  673. getTouchNode: function(touchX, touchY) {
  674. var nodes = this.nodeData
  675. for (var i = 0; i < nodes.length; i++) {
  676. var node = nodes[i]
  677. var dx = touchX - node.x
  678. var dy = touchY - node.y
  679. var dist = Math.sqrt(dx * dx + dy * dy)
  680. if (dist <= node.radius + 8) {
  681. return node
  682. }
  683. }
  684. return null
  685. },
  686. onTouchStart: function(e) {
  687. if (!this.interactive) return
  688. var touch = e.touches ? e.touches[0] : e.detail
  689. if (!touch) return
  690. var self = this
  691. var rect = {}
  692. var query = uni.createSelectorQuery().in(this)
  693. query.select('#forceGraphCanvas').boundingClientRect()
  694. query.exec(function(res) {
  695. if (res && res[0]) {
  696. rect = res[0]
  697. var x = touch.clientX - rect.left
  698. var y = touch.clientY - rect.top
  699. var node = self.getTouchNode(x, y)
  700. if (node) {
  701. if (node.isSelf) {
  702. // 自身节点 → 显示 + 号
  703. self.touchingSelf = true
  704. } else {
  705. // 其他节点 → 拖拽(若模拟已因收敛停止,则唤醒)
  706. if (!self.isSimulating) {
  707. self.startSimulation()
  708. }
  709. self.dragging = {
  710. node: node,
  711. offsetX: x - node.x,
  712. offsetY: y - node.y
  713. }
  714. self.dragStartPos = { x: x, y: y }
  715. node.fx = node.x
  716. node.fy = node.y
  717. node.fixed = true
  718. }
  719. }
  720. }
  721. }.bind(this))
  722. },
  723. onTouchMove: function(e) {
  724. if (!this.dragging) return
  725. e.preventDefault && e.preventDefault()
  726. var touch = e.touches ? e.touches[0] : e.detail
  727. if (!touch) return
  728. var rect = {}
  729. var self = this
  730. var query = uni.createSelectorQuery().in(this)
  731. query.select('#forceGraphCanvas').boundingClientRect()
  732. query.exec(function(res) {
  733. if (res && res[0]) {
  734. rect = res[0]
  735. var x = touch.clientX - rect.left
  736. var y = touch.clientY - rect.top
  737. var node = self.dragging.node
  738. node.x = x - self.dragging.offsetX
  739. node.y = y - self.dragging.offsetY
  740. node.fx = node.x
  741. node.fy = node.y
  742. }
  743. }.bind(this))
  744. },
  745. onTouchEnd: function(e) {
  746. // 如果正在触摸自身节点 → 跳转成员维护页
  747. if (this.touchingSelf) {
  748. this.touchingSelf = false
  749. if (this.interactive) {
  750. this.goSelfMaintenance()
  751. }
  752. this.dragging = null
  753. this.dragStartPos = null
  754. return
  755. }
  756. if (!this.dragging) return
  757. var wasDragged = this.dragStartPos && (
  758. Math.abs(this.dragging.node.x - this.dragStartPos.x) > 5 ||
  759. Math.abs(this.dragging.node.y - this.dragStartPos.y) > 5
  760. )
  761. var node = this.dragging.node
  762. node.fixed = false
  763. node.fx = 0
  764. node.fy = 0
  765. // 如果没有真正拖拽(点击),触发 memberTap
  766. if (!wasDragged && this.interactive) {
  767. this.$emit('memberTap', {
  768. memberId: node.id,
  769. memberType: node.memberType,
  770. nickname: node.nickname
  771. })
  772. }
  773. this.dragging = null
  774. this.dragStartPos = null
  775. },
  776. // 跳转到成员维护页面 (点自己进入维护)
  777. goSelfMaintenance: function() {
  778. uni.navigateTo({
  779. url: '/pages/profile-extra/family-members'
  780. })
  781. },
  782. // 点击右上角小齿轮 → 跳转成员管理页
  783. onManageTap: function() {
  784. uni.navigateTo({
  785. url: '/pages/profile-extra/family-members'
  786. })
  787. },
  788. // ===== 工具方法 =====
  789. getEnergy: function(memberId) {
  790. var data = this.energyMap[memberId]
  791. if (!data) return 0
  792. var key = this.dimensionCode + 'Score'
  793. var val = data[key]
  794. return (typeof val !== 'undefined' && val !== null) ? val : 0
  795. },
  796. getIntimacy: function(memberId, key) {
  797. var data = this.intimacyMap[memberId]
  798. if (!data) return null
  799. var val = data[key]
  800. return (typeof val !== 'undefined' && val !== null) ? val : null
  801. },
  802. updateCanvasSize: function() {
  803. var self = this
  804. var cnt = this.members ? this.members.length : 0
  805. self.canvasHeight = Math.max(200, cnt * 90)
  806. var query = uni.createSelectorQuery().in(this)
  807. query.select('.family-graph-wrapper').boundingClientRect(function(rect) {
  808. if (rect) {
  809. self.canvasWidth = rect.width || 340
  810. }
  811. }).exec()
  812. }
  813. }
  814. }
  815. </script>
  816. <style scoped>
  817. .family-graph-wrapper {
  818. position: relative;
  819. width: 100%;
  820. min-height: 200px;
  821. height: auto;
  822. margin: 10rpx 0;
  823. background: #FFFFFF;
  824. border-radius: 24rpx;
  825. overflow: hidden;
  826. }
  827. .family-graph-canvas {
  828. position: absolute;
  829. top: 0;
  830. left: 0;
  831. z-index: 1;
  832. }
  833. /* 右上角小齿轮 */
  834. .gear-icon {
  835. position: absolute;
  836. top: 12rpx;
  837. right: 12rpx;
  838. z-index: 10;
  839. width: 56rpx;
  840. height: 56rpx;
  841. display: flex;
  842. align-items: center;
  843. justify-content: center;
  844. background: rgba(255, 255, 255, 0.9);
  845. border-radius: 50%;
  846. box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  847. }
  848. .gear-text {
  849. font-size: 32rpx;
  850. color: #94A3B8;
  851. }
  852. /* ⚙ 维护页提示 */
  853. .add-hint {
  854. position: absolute;
  855. z-index: 5;
  856. width: 40rpx;
  857. height: 40rpx;
  858. border-radius: 50%;
  859. background: #10B981;
  860. display: flex;
  861. align-items: center;
  862. justify-content: center;
  863. opacity: 0;
  864. transform: scale(0.5);
  865. transition: opacity 0.15s, transform 0.15s;
  866. pointer-events: none;
  867. }
  868. .add-hint.add-hint-visible {
  869. opacity: 1;
  870. transform: scale(1);
  871. }
  872. .add-hint-text {
  873. font-size: 28rpx;
  874. color: #FFFFFF;
  875. font-weight: bold;
  876. line-height: 1;
  877. }
  878. .family-graph-empty {
  879. display: flex;
  880. align-items: center;
  881. justify-content: center;
  882. padding: 60rpx 0;
  883. background: #FFFFFF;
  884. border-radius: 24rpx;
  885. margin: 10rpx 0;
  886. }
  887. .empty-text {
  888. font-size: 28rpx;
  889. color: #94A3B8;
  890. }
  891. </style>