LineGrayscaleMeasurementTool.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. import { Point3, Point2 } from './mathUtils';
  2. import {
  3. utilities as csUtils,
  4. Types as CoreTypes,
  5. getEnabledElement,
  6. cache,
  7. } from '@cornerstonejs/core';
  8. import * as cornerstone from '@cornerstonejs/core';
  9. import {
  10. AnnotationTool,
  11. utilities,
  12. Types,
  13. annotation,
  14. drawing,
  15. } from '@cornerstonejs/tools';
  16. const {
  17. drawHandles,
  18. drawLinkedTextBox,
  19. drawLine: drawLineSvg,
  20. } = drawing;
  21. import {
  22. PublicToolProps,
  23. ToolProps,
  24. EventTypes,
  25. SVGDrawingHelper,
  26. } from '@cornerstonejs/tools/dist/esm/types';
  27. /**
  28. * 直线灰度测量注解接口
  29. */
  30. interface LineGrayscaleAnnotation extends Types.Annotation {
  31. data: {
  32. handles: {
  33. // 控制点(两个端点,世界坐标)
  34. points: CoreTypes.Point3[];
  35. // 当前激活的手柄索引(0或1,null表示未激活)
  36. activeHandleIndex: number | null;
  37. };
  38. label?: string;
  39. // 文本框位置(Canvas坐标)
  40. textBox?: CoreTypes.Point2;
  41. // 缓存的统计结果
  42. cachedStats?: {
  43. [targetId: string]: {
  44. // 平均灰度值
  45. mean: number;
  46. // 最小灰度值
  47. min: number;
  48. // 最大灰度值
  49. max: number;
  50. // 采样点数量
  51. sampleCount: number;
  52. // 直线长度(mm)
  53. lineLength: number;
  54. };
  55. };
  56. };
  57. }
  58. /**
  59. * 像素采样结果
  60. */
  61. interface PixelSampleResult {
  62. values: number[];
  63. coordinates: Array<{ x: number; y: number }>;
  64. count: number;
  65. }
  66. /**
  67. * 直线灰度测量工具
  68. * 功能: 在医学影像上绘制直线,计算并显示直线路径上的灰度值统计信息
  69. */
  70. export default class LineGrayscaleMeasurementTool extends AnnotationTool {
  71. static toolName = 'LineGrayscaleMeasurementTool';
  72. editData: {
  73. annotation: Types.Annotation;
  74. viewportIdsToRender: string[];
  75. handleIndex?: number;
  76. newAnnotation?: boolean;
  77. hasMoved?: boolean;
  78. textBoxBeingMoved?: boolean;
  79. textBoxOffset?: CoreTypes.Point2;
  80. wholeToolOffset?: CoreTypes.Point2;
  81. originalPoints?: CoreTypes.Point3[]; // 保存拖拽开始时的原始点坐标
  82. } | null = null;
  83. isDrawing: boolean = false;
  84. /**
  85. * 创建默认注解(工具激活时自动创建)
  86. */
  87. static createDefaultAnnotation(
  88. element: HTMLDivElement,
  89. viewport: CoreTypes.IStackViewport | CoreTypes.IVolumeViewport
  90. ): LineGrayscaleAnnotation {
  91. const enabledElement = getEnabledElement(element);
  92. if (!enabledElement) {
  93. throw new Error('Element is not enabled');
  94. }
  95. // 获取viewport的尺寸
  96. const canvas = viewport.canvas;
  97. const { width, height } = canvas;
  98. const centerX = width / 2;
  99. const centerY = height / 2;
  100. // 设置起点和终点(Canvas坐标,水平线,长度100px)
  101. const startCanvas: CoreTypes.Point2 = [centerX - 50, centerY];
  102. const endCanvas: CoreTypes.Point2 = [centerX + 50, centerY];
  103. // 转换为世界坐标
  104. const startWorld = viewport.canvasToWorld(startCanvas);
  105. const endWorld = viewport.canvasToWorld(endCanvas);
  106. const camera = viewport.getCamera();
  107. const { viewPlaneNormal, viewUp } = camera;
  108. if (viewPlaneNormal === undefined || viewUp === undefined) {
  109. throw new Error('Camera parameters are undefined');
  110. }
  111. // 创建注解对象
  112. const annotationData = {
  113. invalidated: true,
  114. highlighted: false,
  115. metadata: {
  116. viewPlaneNormal: [...viewPlaneNormal] as CoreTypes.Point3,
  117. viewUp: [...viewUp] as CoreTypes.Point3,
  118. FrameOfReferenceUID: viewport.getFrameOfReferenceUID(),
  119. referencedImageId: viewport.getCurrentImageId?.() || '',
  120. toolName: LineGrayscaleMeasurementTool.toolName,
  121. },
  122. data: {
  123. label: '',
  124. handles: {
  125. points: [startWorld, endWorld],
  126. activeHandleIndex: null,
  127. },
  128. cachedStats: {},
  129. },
  130. } as LineGrayscaleAnnotation;
  131. return annotationData;
  132. }
  133. constructor(
  134. toolProps: PublicToolProps = {},
  135. defaultToolProps: ToolProps = {
  136. supportedInteractionTypes: ['Mouse', 'Touch'],
  137. configuration: {
  138. shadow: true,
  139. preventHandleOutsideImage: false,
  140. },
  141. }
  142. ) {
  143. super(toolProps, defaultToolProps);
  144. }
  145. /**
  146. * 禁用手动绘制(仅支持预设注解)
  147. */
  148. addNewAnnotation(
  149. evt: EventTypes.InteractionEventType
  150. ): LineGrayscaleAnnotation {
  151. evt.preventDefault();
  152. return {} as LineGrayscaleAnnotation;
  153. }
  154. /**
  155. * 检查点是否靠近工具
  156. */
  157. isPointNearTool(
  158. element: HTMLDivElement,
  159. annotation: LineGrayscaleAnnotation,
  160. canvasCoords: CoreTypes.Point2,
  161. proximity: number
  162. ): boolean {
  163. const enabledElement = getEnabledElement(element);
  164. if (!enabledElement) {
  165. return false;
  166. }
  167. const { viewport } = enabledElement;
  168. const points = annotation.data.handles.points;
  169. // 检查是否靠近任意一个手柄点
  170. for (let i = 0; i < points.length; i++) {
  171. const point = points[i];
  172. const canvasPoint = viewport.worldToCanvas(point);
  173. const distance = Math.sqrt(
  174. Math.pow(canvasPoint[0] - canvasCoords[0], 2) +
  175. Math.pow(canvasPoint[1] - canvasCoords[1], 2)
  176. );
  177. if (distance < proximity) {
  178. return true;
  179. }
  180. }
  181. // 检查是否靠近直线
  182. if (points.length >= 2) {
  183. const p1Canvas = viewport.worldToCanvas(points[0]);
  184. const p2Canvas = viewport.worldToCanvas(points[1]);
  185. const dist = this._distanceToSegment(canvasCoords, p1Canvas, p2Canvas);
  186. if (dist < proximity) {
  187. return true;
  188. }
  189. }
  190. return false;
  191. }
  192. /**
  193. * 计算点到线段的距离
  194. */
  195. private _distanceToSegment(
  196. point: CoreTypes.Point2,
  197. lineStart: CoreTypes.Point2,
  198. lineEnd: CoreTypes.Point2
  199. ): number {
  200. const x = point[0];
  201. const y = point[1];
  202. const x1 = lineStart[0];
  203. const y1 = lineStart[1];
  204. const x2 = lineEnd[0];
  205. const y2 = lineEnd[1];
  206. const A = x - x1;
  207. const B = y - y1;
  208. const C = x2 - x1;
  209. const D = y2 - y1;
  210. const dot = A * C + B * D;
  211. const lenSq = C * C + D * D;
  212. let param = -1;
  213. if (lenSq !== 0) {
  214. param = dot / lenSq;
  215. }
  216. let xx, yy;
  217. if (param < 0) {
  218. xx = x1;
  219. yy = y1;
  220. } else if (param > 1) {
  221. xx = x2;
  222. yy = y2;
  223. } else {
  224. xx = x1 + param * C;
  225. yy = y1 + param * D;
  226. }
  227. const dx = x - xx;
  228. const dy = y - yy;
  229. return Math.sqrt(dx * dx + dy * dy);
  230. }
  231. /**
  232. * 取消操作
  233. */
  234. cancel(element: HTMLDivElement): string {
  235. if (this.isDrawing) {
  236. this.isDrawing = false;
  237. this._deactivateDraw(element);
  238. this._deactivateModify(element);
  239. const enabledElement = getEnabledElement(element);
  240. if (enabledElement) {
  241. const viewportIdsToRender =
  242. utilities.viewportFilters.getViewportIdsWithToolToRender(
  243. element,
  244. this.getToolName()
  245. );
  246. utilities.triggerAnnotationRenderForViewportIds(
  247. viewportIdsToRender
  248. );
  249. }
  250. this.editData = null;
  251. return this.getToolName();
  252. }
  253. return '';
  254. }
  255. _activateDraw(element: HTMLDivElement): void {
  256. element.addEventListener(
  257. 'CORNERSTONE_TOOLS_MOUSE_DRAG',
  258. this._dragCallback as EventListener
  259. );
  260. element.addEventListener(
  261. 'CORNERSTONE_TOOLS_MOUSE_UP',
  262. this._endCallback as EventListener
  263. );
  264. }
  265. _deactivateDraw(element: HTMLDivElement): void {
  266. element.removeEventListener(
  267. 'CORNERSTONE_TOOLS_MOUSE_DRAG',
  268. this._dragCallback as EventListener
  269. );
  270. element.removeEventListener(
  271. 'CORNERSTONE_TOOLS_MOUSE_UP',
  272. this._endCallback as EventListener
  273. );
  274. }
  275. _activateModify(element: HTMLDivElement): void {
  276. element.addEventListener(
  277. 'CORNERSTONE_TOOLS_MOUSE_DOWN',
  278. this._mouseDownModifyCallback as EventListener
  279. );
  280. element.addEventListener(
  281. 'CORNERSTONE_TOOLS_MOUSE_DRAG',
  282. this._mouseDragModifyCallback as EventListener
  283. );
  284. element.addEventListener(
  285. 'CORNERSTONE_TOOLS_MOUSE_UP',
  286. this._mouseUpModifyCallback as EventListener
  287. );
  288. element.addEventListener(
  289. 'CORNERSTONE_TOOLS_MOUSE_MOVE',
  290. this._mouseMoveModifyCallback as EventListener
  291. );
  292. element.addEventListener(
  293. 'keydown',
  294. this._keyDownCallback as EventListener
  295. );
  296. }
  297. _deactivateModify(element: HTMLDivElement): void {
  298. element.removeEventListener(
  299. 'CORNERSTONE_TOOLS_MOUSE_DOWN',
  300. this._mouseDownModifyCallback as EventListener
  301. );
  302. element.removeEventListener(
  303. 'CORNERSTONE_TOOLS_MOUSE_DRAG',
  304. this._mouseDragModifyCallback as EventListener
  305. );
  306. element.removeEventListener(
  307. 'CORNERSTONE_TOOLS_MOUSE_UP',
  308. this._mouseUpModifyCallback as EventListener
  309. );
  310. element.removeEventListener(
  311. 'CORNERSTONE_TOOLS_MOUSE_MOVE',
  312. this._mouseMoveModifyCallback as EventListener
  313. );
  314. element.removeEventListener(
  315. 'keydown',
  316. this._keyDownCallback as EventListener
  317. );
  318. }
  319. _mouseDownModifyCallback = (evt: EventTypes.InteractionEventType): void => {
  320. const eventDetail = evt.detail;
  321. const { element, currentPoints } = eventDetail;
  322. const canvasCoords = currentPoints.canvas;
  323. const enabledElement = getEnabledElement(element);
  324. if (!enabledElement) {
  325. return;
  326. }
  327. const { viewport } = enabledElement;
  328. const annotations = annotation.state.getAnnotations(this.getToolName(), element);
  329. if (!annotations || annotations.length === 0) {
  330. return;
  331. }
  332. // 查找最近的手柄或工具
  333. for (const ann of annotations) {
  334. const customAnn = ann as LineGrayscaleAnnotation;
  335. // 1. 检查是否点击在文本框上
  336. // 使用默认位置(第二个端点)如果 textBox 未定义
  337. const textBoxCanvas = customAnn.data.textBox || viewport.worldToCanvas(customAnn.data.handles.points[1]);
  338. if (this._isPointNearTextBox(canvasCoords, textBoxCanvas)) {
  339. const viewportIdsToRender =
  340. utilities.viewportFilters.getViewportIdsWithToolToRender(
  341. element,
  342. this.getToolName()
  343. );
  344. this.editData = {
  345. annotation: customAnn,
  346. viewportIdsToRender,
  347. textBoxBeingMoved: true,
  348. textBoxOffset: [
  349. canvasCoords[0] - textBoxCanvas[0],
  350. canvasCoords[1] - textBoxCanvas[1],
  351. ],
  352. hasMoved: false,
  353. };
  354. customAnn.isSelected = true;
  355. customAnn.highlighted = true;
  356. utilities.triggerAnnotationRenderForViewportIds(
  357. viewportIdsToRender
  358. );
  359. evt.preventDefault();
  360. evt.stopPropagation();
  361. return;
  362. }
  363. // 2. 检查是否点击在手柄上
  364. const handle = this.getHandleNearImagePoint(
  365. element,
  366. customAnn,
  367. canvasCoords,
  368. 6
  369. );
  370. if (handle) {
  371. const viewportIdsToRender =
  372. utilities.viewportFilters.getViewportIdsWithToolToRender(
  373. element,
  374. this.getToolName()
  375. );
  376. this.editData = {
  377. annotation: customAnn,
  378. viewportIdsToRender,
  379. handleIndex: customAnn.data.handles.activeHandleIndex || 0,
  380. hasMoved: false,
  381. originalPoints: [...customAnn.data.handles.points],
  382. };
  383. customAnn.isSelected = true;
  384. customAnn.highlighted = true;
  385. utilities.triggerAnnotationRenderForViewportIds(
  386. viewportIdsToRender
  387. );
  388. evt.preventDefault();
  389. evt.stopPropagation();
  390. return;
  391. }
  392. // 3. 检查是否点击在线段上(拖拽整个工具)
  393. if (this.isPointNearTool(element, customAnn, canvasCoords, 10)) {
  394. const viewportIdsToRender =
  395. utilities.viewportFilters.getViewportIdsWithToolToRender(
  396. element,
  397. this.getToolName()
  398. );
  399. // 计算线段中心点
  400. const points = customAnn.data.handles.points;
  401. const centerWorld: CoreTypes.Point3 = [
  402. (points[0][0] + points[1][0]) / 2,
  403. (points[0][1] + points[1][1]) / 2,
  404. (points[0][2] + points[1][2]) / 2,
  405. ];
  406. const centerCanvas = viewport.worldToCanvas(centerWorld);
  407. const wholeToolOffset: CoreTypes.Point2 = [
  408. canvasCoords[0] - centerCanvas[0],
  409. canvasCoords[1] - centerCanvas[1],
  410. ];
  411. // 开始拖拽整个工具
  412. this.editData = {
  413. annotation: customAnn,
  414. viewportIdsToRender,
  415. handleIndex: -1, // -1表示拖拽整个工具
  416. hasMoved: false,
  417. wholeToolOffset: wholeToolOffset,
  418. };
  419. customAnn.isSelected = true;
  420. customAnn.highlighted = true;
  421. utilities.triggerAnnotationRenderForViewportIds(
  422. viewportIdsToRender
  423. );
  424. evt.preventDefault();
  425. evt.stopPropagation();
  426. return;
  427. }
  428. }
  429. // 如果没有点击在工具上,取消所有选中状态
  430. for (const ann of annotations) {
  431. const customAnn = ann as LineGrayscaleAnnotation;
  432. customAnn.isSelected = false;
  433. }
  434. const viewportIdsToRender =
  435. utilities.viewportFilters.getViewportIdsWithToolToRender(
  436. element,
  437. this.getToolName()
  438. );
  439. utilities.triggerAnnotationRenderForViewportIds(viewportIdsToRender);
  440. };
  441. _mouseDragModifyCallback = (evt: EventTypes.InteractionEventType): void => {
  442. if (!this.editData) {
  443. return;
  444. }
  445. const eventDetail = evt.detail;
  446. const { currentPoints } = eventDetail;
  447. const canvasCoords = currentPoints.canvas;
  448. const enabledElement = getEnabledElement(eventDetail.element);
  449. if (!enabledElement) {
  450. return;
  451. }
  452. const { viewport } = enabledElement;
  453. const { annotation: ann, viewportIdsToRender } = this.editData;
  454. const customAnn = ann as LineGrayscaleAnnotation;
  455. const { data } = customAnn;
  456. // 1. 处理文本框拖拽
  457. if (this.editData.textBoxBeingMoved && this.editData.textBoxOffset) {
  458. const newTextBoxPosition: CoreTypes.Point2 = [
  459. canvasCoords[0] - this.editData.textBoxOffset[0],
  460. canvasCoords[1] - this.editData.textBoxOffset[1],
  461. ];
  462. data.textBox = newTextBoxPosition;
  463. this.editData.hasMoved = true;
  464. utilities.triggerAnnotationRenderForViewportIds(
  465. viewportIdsToRender
  466. );
  467. evt.preventDefault();
  468. evt.stopPropagation();
  469. return;
  470. }
  471. // 2. 处理整个工具的平移
  472. if (this.editData.handleIndex === -1 && this.editData.wholeToolOffset) {
  473. // 计算新的中心位置
  474. const newCenterCanvas: CoreTypes.Point2 = [
  475. canvasCoords[0] - this.editData.wholeToolOffset[0],
  476. canvasCoords[1] - this.editData.wholeToolOffset[1],
  477. ];
  478. const newCenterWorld = viewport.canvasToWorld(newCenterCanvas);
  479. // 计算当前中心位置
  480. const points = data.handles.points;
  481. const currentCenterWorld: CoreTypes.Point3 = [
  482. (points[0][0] + points[1][0]) / 2,
  483. (points[0][1] + points[1][1]) / 2,
  484. (points[0][2] + points[1][2]) / 2,
  485. ];
  486. // 计算偏移量
  487. const worldOffset: CoreTypes.Point3 = [
  488. newCenterWorld[0] - currentCenterWorld[0],
  489. newCenterWorld[1] - currentCenterWorld[1],
  490. 0,
  491. ];
  492. // 应用偏移到所有点
  493. for (let i = 0; i < data.handles.points.length; i++) {
  494. data.handles.points[i] = [
  495. data.handles.points[i][0] + worldOffset[0],
  496. data.handles.points[i][1] + worldOffset[1],
  497. data.handles.points[i][2],
  498. ] as CoreTypes.Point3;
  499. }
  500. this.editData.hasMoved = true;
  501. utilities.triggerAnnotationRenderForViewportIds(
  502. viewportIdsToRender
  503. );
  504. evt.preventDefault();
  505. evt.stopPropagation();
  506. return;
  507. }
  508. // 3. 处理手柄拖拽
  509. const worldPos = currentPoints.world;
  510. const activeHandleIndex = data.handles.activeHandleIndex;
  511. if (activeHandleIndex !== null && activeHandleIndex >= 0 && activeHandleIndex < data.handles.points.length) {
  512. data.handles.points[activeHandleIndex] = worldPos;
  513. this.editData.hasMoved = true;
  514. utilities.triggerAnnotationRenderForViewportIds(
  515. viewportIdsToRender
  516. );
  517. evt.preventDefault();
  518. evt.stopPropagation();
  519. }
  520. };
  521. _mouseUpModifyCallback = (evt: EventTypes.InteractionEventType): void => {
  522. if (!this.editData) {
  523. return;
  524. }
  525. const { annotation: ann, hasMoved } = this.editData;
  526. const customAnn = ann as LineGrayscaleAnnotation;
  527. customAnn.data.handles.activeHandleIndex = null;
  528. customAnn.highlighted = false;
  529. const eventDetail = evt.detail;
  530. const { element } = eventDetail;
  531. const enabledElement = getEnabledElement(element);
  532. // 如果工具被移动了,更新缓存的统计数据
  533. if (hasMoved && enabledElement && !this.editData.textBoxBeingMoved) {
  534. this._updateCachedStats(customAnn, enabledElement);
  535. }
  536. const viewportIdsToRender =
  537. utilities.viewportFilters.getViewportIdsWithToolToRender(
  538. element,
  539. this.getToolName()
  540. );
  541. utilities.triggerAnnotationRenderForViewportIds(
  542. viewportIdsToRender
  543. );
  544. this.editData = null;
  545. evt.preventDefault();
  546. evt.stopPropagation();
  547. };
  548. _mouseMoveModifyCallback = (evt: EventTypes.InteractionEventType): void => {
  549. const eventDetail = evt.detail;
  550. const { element, currentPoints } = eventDetail;
  551. if (!currentPoints || !currentPoints.canvas) {
  552. return;
  553. }
  554. const canvasCoords = currentPoints.canvas;
  555. const enabledElement = getEnabledElement(element);
  556. if (!enabledElement) {
  557. return;
  558. }
  559. const { viewport } = enabledElement;
  560. const annotations = annotation.state.getAnnotations(this.getToolName(), element);
  561. if (!annotations || annotations.length === 0) {
  562. element.style.cursor = 'default';
  563. return;
  564. }
  565. let isHovering = false;
  566. let cursorSet = false;
  567. // 检查是否悬停在文本、手柄或直线上
  568. for (const ann of annotations) {
  569. const customAnn = ann as LineGrayscaleAnnotation;
  570. // 1. 检查是否悬停在文本框上
  571. // 使用默认位置(第二个端点)如果 textBox 未定义
  572. const textBoxCanvas = customAnn.data.textBox || viewport.worldToCanvas(customAnn.data.handles.points[1]);
  573. if (this._isPointNearTextBox(canvasCoords, textBoxCanvas)) {
  574. element.style.cursor = 'pointer';
  575. customAnn.highlighted = true;
  576. isHovering = true;
  577. cursorSet = true;
  578. break;
  579. }
  580. // 2. 检查是否靠近手柄
  581. const handle = this.getHandleNearImagePoint(element, customAnn, canvasCoords, 6);
  582. if (handle) {
  583. element.style.cursor = 'crosshair';
  584. customAnn.highlighted = true;
  585. isHovering = true;
  586. cursorSet = true;
  587. break;
  588. }
  589. // 3. 检查是否靠近直线
  590. if (this.isPointNearTool(element, customAnn, canvasCoords, 10)) {
  591. element.style.cursor = 'crosshair';
  592. customAnn.highlighted = true;
  593. isHovering = true;
  594. cursorSet = true;
  595. break;
  596. }
  597. }
  598. // 如果没有悬停,重置高亮和光标
  599. if (!isHovering) {
  600. for (const ann of annotations) {
  601. const customAnn = ann as LineGrayscaleAnnotation;
  602. if (!customAnn.isSelected) {
  603. customAnn.highlighted = false;
  604. }
  605. }
  606. element.style.cursor = 'default';
  607. }
  608. // 触发渲染以更新高亮状态
  609. const viewportIdsToRender = utilities.viewportFilters.getViewportIdsWithToolToRender(
  610. element,
  611. this.getToolName()
  612. );
  613. utilities.triggerAnnotationRenderForViewportIds(viewportIdsToRender);
  614. };
  615. _keyDownCallback = (evt: KeyboardEvent): void => {
  616. if (evt.key === 'Delete') {
  617. const element = document.activeElement as HTMLDivElement;
  618. if (!element) return;
  619. const annotations = annotation.state.getAnnotations(this.getToolName(), element);
  620. // 查找选中的注解
  621. const selectedAnnotation = annotations.find(ann => ann.isSelected);
  622. if (selectedAnnotation) {
  623. // 删除选中的注解
  624. annotation.state.removeAnnotation(selectedAnnotation.annotationUID || '');
  625. // 触发视图更新
  626. const viewportIdsToRender =
  627. utilities.viewportFilters.getViewportIdsWithToolToRender(
  628. element,
  629. this.getToolName()
  630. );
  631. utilities.triggerAnnotationRenderForViewportIds(viewportIdsToRender);
  632. evt.preventDefault();
  633. evt.stopPropagation();
  634. }
  635. }
  636. };
  637. handleSelectedCallback(
  638. evt: EventTypes.InteractionEventType,
  639. annotation: LineGrayscaleAnnotation
  640. ): void {
  641. const eventDetail = evt.detail;
  642. const { element } = eventDetail;
  643. annotation.highlighted = true;
  644. const viewportIdsToRender =
  645. utilities.viewportFilters.getViewportIdsWithToolToRender(
  646. element,
  647. this.getToolName()
  648. );
  649. utilities.triggerAnnotationRenderForViewportIds(
  650. viewportIdsToRender
  651. );
  652. evt.preventDefault();
  653. }
  654. toolSelectedCallback(
  655. evt: EventTypes.InteractionEventType,
  656. annotation: LineGrayscaleAnnotation
  657. ): void {
  658. // 实现工具选中逻辑
  659. }
  660. _dragCallback = (evt: EventTypes.InteractionEventType): void => {
  661. this.isDrawing = true;
  662. // 实现拖拽逻辑
  663. };
  664. _endCallback = (evt: EventTypes.InteractionEventType): void => {
  665. // 实现结束逻辑
  666. };
  667. getHandleNearImagePoint(
  668. element: HTMLDivElement,
  669. annotation: LineGrayscaleAnnotation,
  670. canvasCoords: CoreTypes.Point2,
  671. proximity: number
  672. ): Types.ToolHandle | undefined {
  673. const enabledElement = getEnabledElement(element);
  674. if (!enabledElement) {
  675. return undefined;
  676. }
  677. const { viewport } = enabledElement;
  678. const points = annotation.data.handles.points;
  679. const handleProximity = Math.max(proximity, 15);
  680. for (let i = 0; i < points.length; i++) {
  681. const point = points[i];
  682. const canvasPoint = viewport.worldToCanvas(point);
  683. const distance = Math.sqrt(
  684. Math.pow(canvasPoint[0] - canvasCoords[0], 2) +
  685. Math.pow(canvasPoint[1] - canvasCoords[1], 2)
  686. );
  687. if (distance < handleProximity) {
  688. annotation.data.handles.activeHandleIndex = i;
  689. return {
  690. worldPosition: point,
  691. } as Types.ToolHandle;
  692. }
  693. }
  694. annotation.data.handles.activeHandleIndex = null;
  695. return undefined;
  696. }
  697. /**
  698. * 检查点是否靠近文本框
  699. */
  700. private _isPointNearTextBox(
  701. point: CoreTypes.Point2,
  702. textBoxPosition: CoreTypes.Point2,
  703. padding: number = 10
  704. ): boolean {
  705. // 简单的矩形碰撞检测,假设文本框大小约为 150x80
  706. const textBoxWidth = 150;
  707. const textBoxHeight = 80;
  708. return (
  709. point[0] >= textBoxPosition[0] - padding &&
  710. point[0] <= textBoxPosition[0] + textBoxWidth + padding &&
  711. point[1] >= textBoxPosition[1] - padding &&
  712. point[1] <= textBoxPosition[1] + textBoxHeight + padding
  713. );
  714. }
  715. /**
  716. * 更新缓存的统计数据
  717. */
  718. private _updateCachedStats(
  719. annotation: LineGrayscaleAnnotation,
  720. enabledElement: CoreTypes.IEnabledElement
  721. ): void {
  722. const { viewport } = enabledElement;
  723. const { points } = annotation.data.handles;
  724. if (points.length < 2) {
  725. return;
  726. }
  727. // 使用Cornerstone缓存系统获取图像
  728. const imageId = viewport.getCurrentImageId?.();
  729. if (!imageId) {
  730. console.warn('[LineGrayscaleTool] No imageId available');
  731. return;
  732. }
  733. const image = cornerstone.cache.getImage(imageId);
  734. if (!image) {
  735. console.warn('[LineGrayscaleTool] Image not found in cache');
  736. return;
  737. }
  738. // 采样像素
  739. const sampleResult = this._samplePixelsAlongLine(points[0], points[1], image, viewport);
  740. // 计算统计值
  741. const stats = this._calculateGrayscaleStats(sampleResult.values, points[0], points[1]);
  742. // 更新缓存
  743. const targetId = `imageId:${imageId}`;
  744. if (!annotation.data.cachedStats) {
  745. annotation.data.cachedStats = {};
  746. }
  747. annotation.data.cachedStats[targetId] = stats;
  748. }
  749. /**
  750. * 沿直线采样像素(Bresenham算法)
  751. */
  752. private _samplePixelsAlongLine(
  753. startWorld: CoreTypes.Point3,
  754. endWorld: CoreTypes.Point3,
  755. image: any,
  756. viewport: CoreTypes.IStackViewport | CoreTypes.IVolumeViewport
  757. ): PixelSampleResult {
  758. // 使用正确的API获取像素数据
  759. const pixelData = image.getPixelData();
  760. const { width, height } = image;
  761. // 使用viewport坐标转换(世界坐标→Canvas坐标)
  762. const startCanvas = viewport.worldToCanvas(startWorld);
  763. const endCanvas = viewport.worldToCanvas(endWorld);
  764. // Canvas坐标直接对应像素坐标(对于2D视图)
  765. const startPixel = [
  766. Math.floor(startCanvas[0]),
  767. Math.floor(startCanvas[1]),
  768. ];
  769. const endPixel = [
  770. Math.floor(endCanvas[0]),
  771. Math.floor(endCanvas[1]),
  772. ];
  773. // Bresenham直线算法
  774. const pixels = this._bresenhamLine(
  775. startPixel[0],
  776. startPixel[1],
  777. endPixel[0],
  778. endPixel[1]
  779. );
  780. // 采样灰度值
  781. const values: number[] = [];
  782. const coordinates: Array<{ x: number; y: number }> = [];
  783. for (const pixel of pixels) {
  784. const { x, y } = pixel;
  785. // 边界检查
  786. if (x < 0 || x >= width || y < 0 || y >= height) {
  787. continue;
  788. }
  789. // 计算像素索引(行优先)
  790. const index = y * width + x;
  791. const value = pixelData[index];
  792. values.push(value);
  793. coordinates.push({ x, y });
  794. }
  795. return {
  796. values,
  797. coordinates,
  798. count: values.length,
  799. };
  800. }
  801. /**
  802. * Bresenham直线算法实现
  803. */
  804. private _bresenhamLine(
  805. x0: number,
  806. y0: number,
  807. x1: number,
  808. y1: number
  809. ): Array<{ x: number; y: number }> {
  810. const pixels: Array<{ x: number; y: number }> = [];
  811. const dx = Math.abs(x1 - x0);
  812. const dy = Math.abs(y1 - y0);
  813. const sx = x0 < x1 ? 1 : -1;
  814. const sy = y0 < y1 ? 1 : -1;
  815. let err = dx - dy;
  816. let x = x0;
  817. let y = y0;
  818. while (true) {
  819. pixels.push({ x, y });
  820. if (x === x1 && y === y1) break;
  821. const e2 = 2 * err;
  822. if (e2 > -dy) {
  823. err -= dy;
  824. x += sx;
  825. }
  826. if (e2 < dx) {
  827. err += dx;
  828. y += sy;
  829. }
  830. }
  831. return pixels;
  832. }
  833. /**
  834. * 计算灰度统计值
  835. */
  836. private _calculateGrayscaleStats(
  837. values: number[],
  838. startWorld: CoreTypes.Point3,
  839. endWorld: CoreTypes.Point3
  840. ): {
  841. mean: number;
  842. min: number;
  843. max: number;
  844. sampleCount: number;
  845. lineLength: number;
  846. } {
  847. if (values.length === 0) {
  848. return {
  849. mean: 0,
  850. min: 0,
  851. max: 0,
  852. sampleCount: 0,
  853. lineLength: 0,
  854. };
  855. }
  856. // 计算平均值
  857. const sum = values.reduce((acc, val) => acc + val, 0);
  858. const mean = Math.round(sum / values.length);
  859. // 计算最小值和最大值
  860. const min = Math.min(...values);
  861. const max = Math.max(...values);
  862. // 计算物理距离(mm)
  863. const dx = endWorld[0] - startWorld[0];
  864. const dy = endWorld[1] - startWorld[1];
  865. const dz = endWorld[2] - startWorld[2];
  866. const lineLength = Math.sqrt(dx * dx + dy * dy + dz * dz);
  867. return {
  868. mean,
  869. min,
  870. max,
  871. sampleCount: values.length,
  872. lineLength: parseFloat(lineLength.toFixed(2)),
  873. };
  874. }
  875. /**
  876. * 渲染注解
  877. */
  878. renderAnnotation = (
  879. enabledElement: CoreTypes.IEnabledElement,
  880. svgDrawingHelper: SVGDrawingHelper
  881. ): boolean => {
  882. const { viewport } = enabledElement;
  883. const { element } = viewport;
  884. let annotations = annotation.state.getAnnotations(
  885. LineGrayscaleMeasurementTool.toolName,
  886. element
  887. ) as LineGrayscaleAnnotation[];
  888. if (!annotations || annotations.length === 0) {
  889. return false;
  890. }
  891. const targetId = `imageId:${(viewport as any).getCurrentImageId?.() || ''}`;
  892. const styleSpecifier: any = {
  893. toolGroupId: this.toolGroupId,
  894. toolName: this.getToolName(),
  895. viewportId: viewport.id,
  896. };
  897. for (const annotationItem of annotations) {
  898. const { annotationUID, data } = annotationItem;
  899. const { points } = data.handles;
  900. const canvasCoordinates = points.map((p) => viewport.worldToCanvas(p));
  901. if (!annotationUID) {
  902. continue;
  903. }
  904. styleSpecifier.annotationUID = annotationUID;
  905. const lineWidth = this.getStyle('lineWidth', styleSpecifier, annotationItem);
  906. const lineDash = this.getStyle('lineDash', styleSpecifier, annotationItem);
  907. const color = this.getStyle('color', styleSpecifier, annotationItem);
  908. // 绘制直线
  909. const lineUID = `${annotationUID}-line`;
  910. drawLineSvg(
  911. svgDrawingHelper,
  912. annotationUID,
  913. lineUID,
  914. canvasCoordinates[0],
  915. canvasCoordinates[1],
  916. {
  917. color,
  918. width: lineWidth,
  919. lineDash,
  920. }
  921. );
  922. // 绘制手柄 - 选中时使用更大的半径
  923. const handleGroupUID = `${annotationUID}-handles`;
  924. const handleRadius = annotationItem.isSelected ? 12 : 6;
  925. drawHandles(
  926. svgDrawingHelper,
  927. annotationUID,
  928. handleGroupUID,
  929. canvasCoordinates,
  930. {
  931. color,
  932. handleRadius,
  933. }
  934. );
  935. // 绘制统计文本
  936. const stats = data.cachedStats?.[targetId];
  937. if (stats) {
  938. const textLines = [
  939. `平均: ${stats.mean}`,
  940. `最小: ${stats.min}`,
  941. `最大: ${stats.max}`,
  942. `长度: ${stats.lineLength.toFixed(2)}mm`,
  943. ];
  944. const textBoxPosition = data.textBox || canvasCoordinates[1];
  945. const textBoxUID = `${annotationUID}-text`;
  946. drawLinkedTextBox(
  947. svgDrawingHelper,
  948. annotationUID,
  949. textBoxUID,
  950. textLines,
  951. textBoxPosition,
  952. [canvasCoordinates[1]],
  953. {},
  954. {
  955. color,
  956. }
  957. );
  958. }
  959. }
  960. return true;
  961. };
  962. }