| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484 |
- import { Point3, Point2, fitCircleFrom3Points, vectorAdd, calculateMidpoint, calculateMidpointFor2 } from './mathUtils';
- import {
- utilities as csUtils,
- Types as CoreTypes,
- getEnabledElement,
- } from '@cornerstonejs/core';
- import {
- AnnotationTool,
- utilities,
- Types,
- annotation,
- drawing,
- } from '@cornerstonejs/tools';
- const {
- drawHandles,
- drawLinkedTextBox,
- drawLine: drawLineSvg,
- drawCircle: drawCircleSvg,
- } = drawing;
- import {
- PublicToolProps,
- ToolProps,
- EventTypes,
- SVGDrawingHelper,
- } from '@cornerstonejs/tools/dist/esm/types';
- // 注解初始配置接口
- interface AnnotationInitialConfig {
- acetabulumRadius?: number; // 髋臼圆初始半径(像素)
- femurRadius?: number; // 股骨头圆初始半径(像素)
- circleDistance?: number; // 两圆心之间的初始距离(像素)
- }
- // 注解数据接口
- interface HipDIAnnotation extends Types.Annotation {
- data: {
- handles: {
- points: CoreTypes.Point3[];
- activeHandleIndex: number | null;
- };
- textBox?: CoreTypes.Point2; // DI文本框位置
- cachedStats?: {
- [targetId: string]: {
- acetabulumCircle?: {
- center: CoreTypes.Point3;
- radius: number;
- };
- femurCircle?: {
- center: CoreTypes.Point3;
- radius: number;
- };
- distance: number;
- DI: number;
- };
- };
- };
- }
- // 导出的注解数据接口
- export interface ExportedDIData {
- points: CoreTypes.Point3[]; // 6个点的世界坐标
- circles: {
- acetabulum: {
- center: CoreTypes.Point3;
- radius: number;
- };
- femur: {
- center: CoreTypes.Point3;
- radius: number;
- };
- };
- measurements: {
- distance: number;
- DI: number;
- };
- textBoxPosition?: CoreTypes.Point2;
- metadata: {
- viewPlaneNormal: CoreTypes.Point3;
- viewUp: CoreTypes.Point3;
- FrameOfReferenceUID: string;
- referencedImageId: string;
- };
- }
- export default class HipDIMeasurementTool extends AnnotationTool {
- static toolName = 'HipDIMeasurementTool';
- editData: {
- annotation: Types.Annotation;
- viewportIdsToRender: string[];
- handleIndex?: number;
- newAnnotation?: boolean;
- hasMoved?: boolean;
- textBoxBeingMoved?: boolean;
- textBoxOffset?: CoreTypes.Point2;
- movingWholeTool?: boolean;
- wholeToolOffset?: CoreTypes.Point2;
- } | null = null;
- isDrawing: boolean = false;
- /**
- * 创建一个预设的注解,带有6个默认点
- * @param element HTML元素
- * @param viewport Viewport实例
- * @param config 可选的初始配置
- */
- static createDefaultAnnotation(
- element: HTMLDivElement,
- viewport: CoreTypes.IStackViewport | CoreTypes.IVolumeViewport,
- config?: AnnotationInitialConfig
- ): HipDIAnnotation {
- const enabledElement = getEnabledElement(element);
- if (!enabledElement) {
- throw new Error('Element is not enabled');
- }
- // 获取viewport的尺寸
- const canvas = viewport.canvas;
- const { width, height } = canvas;
- const centerX = width / 2;
- const centerY = height / 2;
- // 应用默认值
- const acetabulumRadius = config?.acetabulumRadius ?? 80;
- const femurRadius = config?.femurRadius ?? 60;
- const circleDistance = config?.circleDistance ?? 100;
- // 创建髋臼圆的3个点(左侧圆,点1,2,3)
- // 在圆周上均匀分布3个点(0度、120度、240度)
- const acetabulumCenterX = centerX - circleDistance / 2;
- const acetabulumCenterY = centerY;
-
- const angle1 = 0;
- const angle2 = (2 * Math.PI) / 3; // 120度
- const angle3 = (4 * Math.PI) / 3; // 240度
- const acetabulumPoints: CoreTypes.Point2[] = [
- [
- acetabulumCenterX + acetabulumRadius * Math.cos(angle1),
- acetabulumCenterY + acetabulumRadius * Math.sin(angle1)
- ],
- [
- acetabulumCenterX + acetabulumRadius * Math.cos(angle2),
- acetabulumCenterY + acetabulumRadius * Math.sin(angle2)
- ],
- [
- acetabulumCenterX + acetabulumRadius * Math.cos(angle3),
- acetabulumCenterY + acetabulumRadius * Math.sin(angle3)
- ]
- ];
- // 创建股骨头圆的3个点(右侧圆,点4,5,6)
- const femurCenterX = centerX + circleDistance / 2;
- const femurCenterY = centerY;
- const femurPoints: CoreTypes.Point2[] = [
- [
- femurCenterX + femurRadius * Math.cos(angle1),
- femurCenterY + femurRadius * Math.sin(angle1)
- ],
- [
- femurCenterX + femurRadius * Math.cos(angle2),
- femurCenterY + femurRadius * Math.sin(angle2)
- ],
- [
- femurCenterX + femurRadius * Math.cos(angle3),
- femurCenterY + femurRadius * Math.sin(angle3)
- ]
- ];
- const canvasPoints: CoreTypes.Point2[] = [
- ...acetabulumPoints,
- ...femurPoints
- ];
- // 转换为world坐标
- const worldPoints = canvasPoints.map((canvasPoint) =>
- viewport.canvasToWorld(canvasPoint)
- );
- const camera = viewport.getCamera();
- const { viewPlaneNormal, viewUp } = camera;
- if (viewPlaneNormal === undefined) {
- throw new Error('viewPlaneNormal is undefined');
- }
- if (viewUp === undefined) {
- throw new Error('viewUp is undefined');
- }
- const annotationData = {
- invalidated: true,
- highlighted: false,
- metadata: {
- viewPlaneNormal: [...viewPlaneNormal] as CoreTypes.Point3,
- viewUp: [...viewUp] as CoreTypes.Point3,
- FrameOfReferenceUID: viewport.getFrameOfReferenceUID(),
- referencedImageId: viewport.getCurrentImageId?.() || '',
- toolName: HipDIMeasurementTool.toolName,
- },
- data: {
- label: '',
- handles: {
- points: worldPoints,
- activeHandleIndex: null,
- },
- cachedStats: {},
- },
- } as HipDIAnnotation;
- return annotationData;
- }
- /**
- * 导出注解数据
- * @param annotation 要导出的注解
- * @returns 导出的数据对象
- */
- static exportAnnotationData(
- annotation: HipDIAnnotation,
- viewport: CoreTypes.IStackViewport | CoreTypes.IVolumeViewport
- ): ExportedDIData | null {
- const targetId = `imageId:${viewport.getCurrentImageId?.() || ''}`;
- const cachedStats = annotation.data.cachedStats?.[targetId];
- if (!cachedStats || !cachedStats.acetabulumCircle || !cachedStats.femurCircle) {
- return null;
- }
- return {
- points: [...annotation.data.handles.points],
- circles: {
- acetabulum: {
- center: cachedStats.acetabulumCircle.center,
- radius: cachedStats.acetabulumCircle.radius,
- },
- femur: {
- center: cachedStats.femurCircle.center,
- radius: cachedStats.femurCircle.radius,
- },
- },
- measurements: {
- distance: cachedStats.distance,
- DI: cachedStats.DI,
- },
- textBoxPosition: annotation.data.textBox,
- metadata: {
- viewPlaneNormal: annotation.metadata?.viewPlaneNormal || [0, 0, 1],
- viewUp: annotation.metadata?.viewUp || [0, 1, 0],
- FrameOfReferenceUID: annotation.metadata?.FrameOfReferenceUID || '',
- referencedImageId: annotation.metadata?.referencedImageId || '',
- },
- };
- }
- /**
- * 从导出的数据恢复注解
- * @param exportedData 导出的数据
- * @param element HTML元素
- * @param viewport Viewport实例
- * @returns 恢复的注解
- */
- static restoreFromExportedData(
- exportedData: ExportedDIData,
- element: HTMLDivElement,
- viewport: CoreTypes.IStackViewport | CoreTypes.IVolumeViewport
- ): HipDIAnnotation {
- const enabledElement = getEnabledElement(element);
- if (!enabledElement) {
- throw new Error('Element is not enabled');
- }
- const annotationData = {
- invalidated: true,
- highlighted: false,
- metadata: {
- ...exportedData.metadata,
- toolName: HipDIMeasurementTool.toolName,
- },
- data: {
- label: '',
- handles: {
- points: [...exportedData.points],
- activeHandleIndex: null,
- },
- textBox: exportedData.textBoxPosition,
- cachedStats: {},
- },
- } as HipDIAnnotation;
- return annotationData;
- }
- constructor(
- toolProps: PublicToolProps = {},
- defaultToolProps: ToolProps = {
- supportedInteractionTypes: ['Mouse', 'Touch'],
- configuration: {
- shadow: true,
- preventHandleOutsideImage: false,
- },
- }
- ) {
- super(toolProps, defaultToolProps);
- }
- /**
- * 添加新注解 - 禁用此功能
- */
- addNewAnnotation(
- evt: EventTypes.InteractionEventType
- ): HipDIAnnotation {
- evt.preventDefault();
- return {} as HipDIAnnotation;
- }
- /**
- * 检查点是否靠近工具
- */
- isPointNearTool(
- element: HTMLDivElement,
- annotation: HipDIAnnotation,
- canvasCoords: CoreTypes.Point2,
- proximity: number
- ): boolean {
- const enabledElement = getEnabledElement(element);
- if (!enabledElement) {
- return false;
- }
- const { viewport } = enabledElement;
- const points = annotation.data.handles.points;
- // 检查是否靠近任意一个手柄点
- for (let i = 0; i < points.length; i++) {
- const point = points[i];
- const canvasPoint = viewport.worldToCanvas(point);
- const distance = Math.sqrt(
- Math.pow(canvasPoint[0] - canvasCoords[0], 2) +
- Math.pow(canvasPoint[1] - canvasCoords[1], 2)
- );
- if (distance < proximity) {
- return true;
- }
- }
- // 检查是否靠近圆心连线
- const targetId = this.getTargetId(viewport);
- const cachedStats = targetId ? annotation.data.cachedStats?.[targetId] : undefined;
- if (cachedStats?.acetabulumCircle && cachedStats?.femurCircle) {
- const M1 = cachedStats.acetabulumCircle.center;
- const M2 = cachedStats.femurCircle.center;
- const M1Canvas = viewport.worldToCanvas(M1);
- const M2Canvas = viewport.worldToCanvas(M2);
- const dist = this._distanceToSegment(canvasCoords, M1Canvas, M2Canvas);
- if (dist < proximity) {
- console.log('靠近圆心连线');
- return true;
- }
- }
- return false;
- }
- /**
- * 检查点击是否在文本框内
- */
- private _isPointInTextBox(
- canvasPoint: CoreTypes.Point2,
- textBoxPosition: CoreTypes.Point2,
- textWidth: number = 100,
- textHeight: number = 40
- ): boolean {
- const [x, y] = canvasPoint;
- const [tx, ty] = textBoxPosition;
- const margin = 10;
- return (
- x >= tx - margin &&
- x <= tx + textWidth + margin &&
- y >= ty - margin &&
- y <= ty + textHeight + margin
- );
- }
- /**
- * 计算点到线段的距离
- */
- private _distanceToSegment(
- point: CoreTypes.Point2,
- lineStart: CoreTypes.Point2,
- lineEnd: CoreTypes.Point2
- ): number {
- const x = point[0];
- const y = point[1];
- const x1 = lineStart[0];
- const y1 = lineStart[1];
- const x2 = lineEnd[0];
- const y2 = lineEnd[1];
- const A = x - x1;
- const B = y - y1;
- const C = x2 - x1;
- const D = y2 - y1;
- const dot = A * C + B * D;
- const lenSq = C * C + D * D;
- let param = -1;
- if (lenSq !== 0) {
- param = dot / lenSq;
- }
- let xx, yy;
- if (param < 0) {
- xx = x1;
- yy = y1;
- } else if (param > 1) {
- xx = x2;
- yy = y2;
- } else {
- xx = x1 + param * C;
- yy = y1 + param * D;
- }
- const dx = x - xx;
- const dy = y - yy;
- return Math.sqrt(dx * dx + dy * dy);
- }
- /**
- * 计算圆在canvas坐标系下的像素半径
- * @param circle 圆的几何信息
- * @param viewport 视口对象
- * @returns 像素半径
- */
- private _getCircleRadiusInPixels(
- circle: { center: CoreTypes.Point3; radius: number },
- viewport: CoreTypes.IStackViewport | CoreTypes.IVolumeViewport
- ): number {
- const { center, radius } = circle;
- // 沿X轴方向获取距离圆心radius的点
- const radiusVector: Point3 = [radius, 0, 0];
- const endPoint: Point3 = vectorAdd(center, radiusVector);
- // 分别转换圆心和圆周上的点到canvas坐标
- const centerCanvas = viewport.worldToCanvas(center);
- const endCanvas = viewport.worldToCanvas(endPoint);
- // 计算两个canvas点之间的距离就是像素半径
- const radiusPixels = Math.sqrt(
- Math.pow(endCanvas[0] - centerCanvas[0], 2) +
- Math.pow(endCanvas[1] - centerCanvas[1], 2)
- );
- return radiusPixels;
- }
- /**
- * 取消操作
- */
- cancel(element: HTMLDivElement): string {
- if (this.isDrawing) {
- this.isDrawing = false;
- this._deactivateDraw(element);
- this._deactivateModify(element);
- const enabledElement = getEnabledElement(element);
- if (enabledElement) {
- const viewportIdsToRender =
- utilities.viewportFilters.getViewportIdsWithToolToRender(
- element,
- this.getToolName()
- );
- utilities.triggerAnnotationRenderForViewportIds(
- viewportIdsToRender
- );
- }
- this.editData = null;
- return this.getToolName();
- }
- return '';
- }
- /**
- * 激活绘制模式
- */
- _activateDraw(element: HTMLDivElement): void {
- element.addEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_DRAG',
- this._dragCallback as EventListener
- );
- element.addEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_UP',
- this._endCallback as EventListener
- );
- element.addEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_CLICK',
- this._endCallback as EventListener
- );
- }
- /**
- * 取消激活绘制模式
- */
- _deactivateDraw(element: HTMLDivElement): void {
- element.removeEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_DRAG',
- this._dragCallback as EventListener
- );
- element.removeEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_UP',
- this._endCallback as EventListener
- );
- element.removeEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_CLICK',
- this._endCallback as EventListener
- );
- }
- /**
- * 激活修改模式
- */
- _activateModify(element: HTMLDivElement): void {
- element.addEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_DOWN',
- this._mouseDownModifyCallback as EventListener
- );
- element.addEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_DRAG',
- this._mouseDragModifyCallback as EventListener
- );
- element.addEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_UP',
- this._mouseUpModifyCallback as EventListener
- );
- element.addEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_MOVE',
- this._mouseMoveModifyCallback as EventListener
- );
- element.addEventListener(
- 'keydown',
- this._keyDownCallback as EventListener
- );
- }
- /**
- * 取消激活修改模式
- */
- _deactivateModify(element: HTMLDivElement): void {
- element.removeEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_DOWN',
- this._mouseDownModifyCallback as EventListener
- );
- element.removeEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_DRAG',
- this._mouseDragModifyCallback as EventListener
- );
- element.removeEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_UP',
- this._mouseUpModifyCallback as EventListener
- );
- element.removeEventListener(
- 'CORNERSTONE_TOOLS_MOUSE_MOVE',
- this._mouseMoveModifyCallback as EventListener
- );
- element.removeEventListener(
- 'keydown',
- this._keyDownCallback as EventListener
- );
- }
- /**
- * 鼠标按下回调 - 用于修改模式
- */
- _mouseDownModifyCallback = (evt: EventTypes.InteractionEventType): void => {
- const eventDetail = evt.detail;
- const { element, currentPoints } = eventDetail;
- const canvasCoords = currentPoints.canvas;
- const enabledElement = getEnabledElement(element);
- if (!enabledElement) {
- return;
- }
- const { viewport } = enabledElement;
- const annotations = annotation.state.getAnnotations(this.getToolName(), element);
-
- if (!annotations || annotations.length === 0) {
- return;
- }
- // 先检查是否点击在文本框上
- for (const ann of annotations) {
- const customAnn = ann as HipDIAnnotation;
- const targetId = this.getTargetId(viewport);
- const cachedStats = targetId ? customAnn.data.cachedStats?.[targetId] : undefined;
- if (cachedStats?.femurCircle) {
- const femurCenterCanvas = viewport.worldToCanvas(cachedStats.femurCircle.center);
- const textBox: CoreTypes.Point2 = customAnn.data.textBox || [
- femurCenterCanvas[0] + 20,
- femurCenterCanvas[1] - 20,
- ];
- if (this._isPointInTextBox(canvasCoords, textBox)) {
- const viewportIdsToRender =
- utilities.viewportFilters.getViewportIdsWithToolToRender(
- element,
- this.getToolName()
- );
- const textBoxOffset: CoreTypes.Point2 = [
- canvasCoords[0] - textBox[0],
- canvasCoords[1] - textBox[1],
- ];
- this.editData = {
- annotation: customAnn,
- viewportIdsToRender,
- hasMoved: false,
- textBoxBeingMoved: true,
- textBoxOffset: textBoxOffset,
- };
- // 点击文本时也选中工具
- customAnn.isSelected = true;
- customAnn.highlighted = true;
- utilities.triggerAnnotationRenderForViewportIds(viewportIdsToRender);
- evt.preventDefault();
- evt.stopPropagation();
- return;
- }
- }
- }
- // 查找最近的手柄
- for (const ann of annotations) {
- const customAnn = ann as HipDIAnnotation;
- const handle = this.getHandleNearImagePoint(
- element,
- customAnn,
- canvasCoords,
- 6
- );
- if (handle) {
- const viewportIdsToRender =
- utilities.viewportFilters.getViewportIdsWithToolToRender(
- element,
- this.getToolName()
- );
- this.editData = {
- annotation: customAnn,
- viewportIdsToRender,
- handleIndex: customAnn.data.handles.activeHandleIndex || 0,
- hasMoved: false,
- };
- customAnn.isSelected = true; // 选中工具
- utilities.triggerAnnotationRenderForViewportIds(
- viewportIdsToRender
- );
- evt.preventDefault();
- evt.stopPropagation();
- return;
- }
- }
- // 如果没有找到手柄,检查是否点击在工具的其他位置(先检测圆周,再检测连线)
- for (const ann of annotations) {
- const customAnn = ann as HipDIAnnotation;
- const targetId = this.getTargetId(viewport);
- const cachedStats = targetId ? customAnn.data.cachedStats?.[targetId] : undefined;
- // 检查是否点击在圆周上
- if (cachedStats?.acetabulumCircle && cachedStats?.femurCircle) {
- const acetabulumCenterCanvas = viewport.worldToCanvas(cachedStats.acetabulumCircle.center);
- const femurCenterCanvas = viewport.worldToCanvas(cachedStats.femurCircle.center);
- // 计算鼠标点到髋臼圆心的距离
- const distanceToAcetabulum = Math.sqrt(
- Math.pow(canvasCoords[0] - acetabulumCenterCanvas[0], 2) +
- Math.pow(canvasCoords[1] - acetabulumCenterCanvas[1], 2)
- );
- // 计算鼠标点到股骨头圆心的距离
- const distanceToFemur = Math.sqrt(
- Math.pow(canvasCoords[0] - femurCenterCanvas[0], 2) +
- Math.pow(canvasCoords[1] - femurCenterCanvas[1], 2)
- );
- // 使用统一的函数计算像素半径
- const acetabulumRadiusPixels = this._getCircleRadiusInPixels(cachedStats.acetabulumCircle, viewport);
- const femurRadiusPixels = this._getCircleRadiusInPixels(cachedStats.femurCircle, viewport);
- // 定义圆周点击容差(像素)
- const circleTolerance = 8;
- // 检查是否点击在圆周上(允许一定的容差)
- const onAcetabulumCircle = Math.abs(distanceToAcetabulum - acetabulumRadiusPixels) <= circleTolerance;
- const onFemurCircle = Math.abs(distanceToFemur - femurRadiusPixels) <= circleTolerance;
- if (onAcetabulumCircle || onFemurCircle) {
- console.log(`在圆周附近 8 px 内`)
- const viewportIdsToRender =
- utilities.viewportFilters.getViewportIdsWithToolToRender(
- element,
- this.getToolName()
- );
- // 使用圆心连线中点作为偏移基准
- const midPointCanvas = calculateMidpointFor2(acetabulumCenterCanvas, femurCenterCanvas);
- const wholeToolOffset: CoreTypes.Point2 = [
- canvasCoords[0] - midPointCanvas[0],
- canvasCoords[1] - midPointCanvas[1],
- ];
- this.editData = {
- annotation: customAnn,
- viewportIdsToRender,
- hasMoved: false,
- movingWholeTool: true,
- wholeToolOffset: wholeToolOffset,
- };
- customAnn.isSelected = true; // 选中工具
- utilities.triggerAnnotationRenderForViewportIds(
- viewportIdsToRender
- );
- evt.preventDefault();
- evt.stopPropagation();
- return;
- }
- }
- // 检查是否点击在圆心连线上
- if (this.isPointNearTool(element, customAnn, canvasCoords, 10)) {
- const viewportIdsToRender =
- utilities.viewportFilters.getViewportIdsWithToolToRender(
- element,
- this.getToolName()
- );
- // 计算鼠标点击位置相对于连线中点的偏移量
- const targetId = this.getTargetId(viewport);
- const cachedStats = targetId ? customAnn.data.cachedStats?.[targetId] : undefined;
- if (cachedStats?.acetabulumCircle && cachedStats.femurCircle) {
- const M1Canvas = viewport.worldToCanvas(cachedStats.acetabulumCircle.center);
- const M2Canvas = viewport.worldToCanvas(cachedStats.femurCircle.center);
- const midPointCanvas = calculateMidpointFor2(M1Canvas, M2Canvas);
- const wholeToolOffset: CoreTypes.Point2 = [
- canvasCoords[0] - midPointCanvas[0],
- canvasCoords[1] - midPointCanvas[1],
- ];
- this.editData = {
- annotation: customAnn,
- viewportIdsToRender,
- hasMoved: false,
- movingWholeTool: true,
- wholeToolOffset: wholeToolOffset,
- };
- customAnn.isSelected = true; // 选中工具
- utilities.triggerAnnotationRenderForViewportIds(
- viewportIdsToRender
- );
- evt.preventDefault();
- evt.stopPropagation();
- return;
- }
- }
- }
- // 如果没有点击在工具上,取消所有工具的选中状态
- for (const ann of annotations) {
- const customAnn = ann as HipDIAnnotation;
- customAnn.isSelected = false;
- }
- };
- /**
- * 鼠标拖拽回调 - 用于修改模式
- */
- _mouseDragModifyCallback = (evt: EventTypes.InteractionEventType): void => {
- if (!this.editData) {
- return;
- }
- const eventDetail = evt.detail;
- const { currentPoints } = eventDetail;
- const canvasCoords = currentPoints.canvas;
- const enabledElement = getEnabledElement(eventDetail.element);
- if (!enabledElement) {
- return;
- }
- const { annotation: ann, viewportIdsToRender, textBoxBeingMoved } = this.editData;
- const customAnn = ann as HipDIAnnotation;
- const { data } = customAnn;
- // 如果正在拖拽文本框
- if (textBoxBeingMoved && this.editData.textBoxOffset) {
- const newTextBoxPosition: CoreTypes.Point2 = [
- canvasCoords[0] - this.editData.textBoxOffset[0],
- canvasCoords[1] - this.editData.textBoxOffset[1],
- ];
- data.textBox = newTextBoxPosition;
- this.editData.hasMoved = true;
- utilities.triggerAnnotationRenderForViewportIds(
- viewportIdsToRender
- );
- evt.preventDefault();
- evt.stopPropagation();
- return;
- }
- // 如果正在移动整个工具
- if (this.editData.movingWholeTool && this.editData.wholeToolOffset) {
- const { viewport } = enabledElement;
- // 计算新的中点位置
- let newMidCanvas: CoreTypes.Point2 = [
- canvasCoords[0] - this.editData.wholeToolOffset[0],
- canvasCoords[1] - this.editData.wholeToolOffset[1],
- ];
- const targetId = this.getTargetId(viewport);
- const cachedStats = targetId ? customAnn.data.cachedStats?.[targetId] : undefined;
- if (cachedStats?.acetabulumCircle && cachedStats.femurCircle) {
- // 获取当前的世界坐标中点
- const M1Canvas = viewport.worldToCanvas(cachedStats.acetabulumCircle.center);
- const M2Canvas = viewport.worldToCanvas(cachedStats.femurCircle.center);
- const oldMidCanvas = calculateMidpointFor2(M1Canvas, M2Canvas);
- // 计算偏移量(新的中点相对旧的中点)
- const offsetCanvas: CoreTypes.Point2 = [
- newMidCanvas[0] - oldMidCanvas[0],
- newMidCanvas[1] - oldMidCanvas[1],
- ];
- // 将canvas偏移转换为world偏移
- const offsetWorld = [
- viewport.canvasToWorld(offsetCanvas)[0] - viewport.canvasToWorld([0, 0])[0],
- viewport.canvasToWorld(offsetCanvas)[1] - viewport.canvasToWorld([0, 0])[1],
- 0, // z轴偏移为0,保持在2D平面上
- ] as CoreTypes.Point3;
- // 应用相同的偏移量给所有相关点
- for (let i = 0; i < data.handles.points.length; i++) {
- data.handles.points[i] = [
- data.handles.points[i][0] + offsetWorld[0],
- data.handles.points[i][1] + offsetWorld[1],
- data.handles.points[i][2],
- ];
- }
- // 更新文本框位置
- if (data.textBox) {
- data.textBox[0] += offsetCanvas[0];
- data.textBox[1] += offsetCanvas[1];
- }
- // 重新计算圆心和统计数据
- this._updateCachedStats(customAnn, enabledElement);
- this.editData.hasMoved = true;
- utilities.triggerAnnotationRenderForViewportIds(
- viewportIdsToRender
- );
- evt.preventDefault();
- evt.stopPropagation();
- return;
- }
- }
- // 处理手柄拖拽
- const worldPos = currentPoints.world;
- const activeHandleIndex = data.handles.activeHandleIndex;
- if (activeHandleIndex !== null && activeHandleIndex >= 0 && activeHandleIndex < data.handles.points.length) {
- data.handles.points[activeHandleIndex] = worldPos;
- this._updateCachedStats(customAnn, enabledElement);
- this.editData.hasMoved = true;
- utilities.triggerAnnotationRenderForViewportIds(
- viewportIdsToRender
- );
- evt.preventDefault();
- evt.stopPropagation();
- }
- };
- /**
- * 鼠标释放回调 - 用于修改模式
- */
- _mouseUpModifyCallback = (evt: EventTypes.InteractionEventType): void => {
- if (!this.editData) {
- return;
- }
- const { annotation: ann } = this.editData;
- const customAnn = ann as HipDIAnnotation;
- customAnn.data.handles.activeHandleIndex = null;
- customAnn.highlighted = false;
- const eventDetail = evt.detail;
- const { element } = eventDetail;
- const viewportIdsToRender =
- utilities.viewportFilters.getViewportIdsWithToolToRender(
- element,
- this.getToolName()
- );
- utilities.triggerAnnotationRenderForViewportIds(
- viewportIdsToRender
- );
- this.editData = null;
- evt.preventDefault();
- evt.stopPropagation();
- };
- /**
- * 鼠标移动回调 - 用于修改模式,处理悬停检测
- * 实现功能1和2:鼠标悬停在文本上时光标为手型,悬停在线段或手柄上时光标为十字准星
- */
- _mouseMoveModifyCallback = (evt: EventTypes.InteractionEventType): void => {
- const eventDetail = evt.detail;
- const { element, currentPoints } = eventDetail;
- if (!currentPoints || !currentPoints.canvas) {
- return;
- }
- const canvasCoords = currentPoints.canvas;
- const enabledElement = getEnabledElement(element);
- if (!enabledElement) {
- return;
- }
- const { viewport } = enabledElement;
- const annotations = annotation.state.getAnnotations(this.getToolName(), element);
- if (!annotations || annotations.length === 0) {
- element.style.cursor = 'default';
- return;
- }
- let isHovering = false;
- // 检查是否悬停在文本框上
- for (const ann of annotations) {
- const customAnn = ann as HipDIAnnotation;
- const targetId = this.getTargetId(viewport);
- const cachedStats = targetId ? customAnn.data.cachedStats?.[targetId] : undefined;
- if (cachedStats?.femurCircle) {
- const femurCenterCanvas = viewport.worldToCanvas(cachedStats.femurCircle.center);
- const textBox: CoreTypes.Point2 = customAnn.data.textBox || [
- femurCenterCanvas[0] + 20,
- femurCenterCanvas[1] - 20,
- ];
- if (this._isPointInTextBox(canvasCoords, textBox)) {
- element.style.cursor = 'pointer'; // 手型光标
- customAnn.highlighted = true;
- isHovering = true;
- break;
- }
- }
- }
- // 如果没有悬停在文本框上,检查是否悬停在手柄、线段或圆周上
- if (!isHovering) {
- for (const ann of annotations) {
- const customAnn = ann as HipDIAnnotation;
- const targetId = this.getTargetId(viewport);
- const cachedStats = targetId ? customAnn.data.cachedStats?.[targetId] : undefined;
- // 检查是否靠近手柄
- const handle = this.getHandleNearImagePoint(element, customAnn, canvasCoords, 6);
- if (handle) {
- element.style.cursor = 'crosshair'; // 十字准星光标
- customAnn.highlighted = true;
- isHovering = true;
- break;
- }
- // 检查是否靠近圆心连线(线段)
- if (this.isPointNearTool(element, customAnn, canvasCoords, 10)) {
- element.style.cursor = 'crosshair'; // 十字准星光标
- customAnn.highlighted = true;
- isHovering = true;
- break;
- }
- // 检查是否悬停在圆周上
- if (cachedStats?.acetabulumCircle && cachedStats?.femurCircle) {
- const acetabulumCenterCanvas = viewport.worldToCanvas(cachedStats.acetabulumCircle.center);
- const femurCenterCanvas = viewport.worldToCanvas(cachedStats.femurCircle.center);
- // 计算鼠标点到圆心的距离
- const distanceToAcetabulum = Math.sqrt(
- Math.pow(canvasCoords[0] - acetabulumCenterCanvas[0], 2) +
- Math.pow(canvasCoords[1] - acetabulumCenterCanvas[1], 2)
- );
- const distanceToFemur = Math.sqrt(
- Math.pow(canvasCoords[0] - femurCenterCanvas[0], 2) +
- Math.pow(canvasCoords[1] - femurCenterCanvas[1], 2)
- );
- // 使用统一的函数计算像素半径
- const acetabulumRadiusPixels = this._getCircleRadiusInPixels(cachedStats.acetabulumCircle, viewport);
- const femurRadiusPixels = this._getCircleRadiusInPixels(cachedStats.femurCircle, viewport);
- // 检查是否悬停在圆周附近(允许一定的容差)
- const hoverTolerance = 8;
- const onAcetabulumCircle = Math.abs(distanceToAcetabulum - acetabulumRadiusPixels) <= hoverTolerance;
- const onFemurCircle = Math.abs(distanceToFemur - femurRadiusPixels) <= hoverTolerance;
- if (onAcetabulumCircle || onFemurCircle) {
- element.style.cursor = 'crosshair'; // 十字准星光标
- customAnn.highlighted = true;
- isHovering = true;
- break;
- }
- }
- }
- }
- // 如果没有悬停在任何地方,重置高亮和光标
- if (!isHovering) {
- for (const ann of annotations) {
- const customAnn = ann as HipDIAnnotation;
- customAnn.highlighted = false;
- }
- element.style.cursor = 'default';
- }
- // 触发渲染以更新高亮状态
- const viewportIdsToRender = utilities.viewportFilters.getViewportIdsWithToolToRender(
- element,
- this.getToolName()
- );
- utilities.triggerAnnotationRenderForViewportIds(viewportIdsToRender);
- };
- /**
- * 键盘事件回调 - 处理delete键删除
- */
- _keyDownCallback = (evt: KeyboardEvent): void => {
- if (evt.key === 'Delete') {
- const element = document.activeElement as HTMLDivElement;
- if (!element) return;
- const annotations = annotation.state.getAnnotations(this.getToolName(), element);
- // 查找选中的注解
- const selectedAnnotation = annotations.find(ann => ann.isSelected);
- if (selectedAnnotation) {
- // 删除选中的注解
- annotation.state.removeAnnotation(selectedAnnotation.annotationUID!);
- // 触发视图更新
- const viewportIdsToRender =
- utilities.viewportFilters.getViewportIdsWithToolToRender(
- element,
- this.getToolName()
- );
- utilities.triggerAnnotationRenderForViewportIds(viewportIdsToRender);
- evt.preventDefault();
- evt.stopPropagation();
- }
- }
- };
- /**
- * 处理选中回调
- */
- handleSelectedCallback(
- evt: EventTypes.InteractionEventType,
- annotation: HipDIAnnotation
- ): void {
- const eventDetail = evt.detail;
- const { element } = eventDetail;
- annotation.highlighted = true;
- const enabledElement = getEnabledElement(element);
- if (!enabledElement) {
- return;
- }
- const viewportIdsToRender =
- utilities.viewportFilters.getViewportIdsWithToolToRender(
- element,
- this.getToolName()
- );
- utilities.triggerAnnotationRenderForViewportIds(
- viewportIdsToRender
- );
- evt.preventDefault();
- }
- /**
- * 工具选中回调
- */
- toolSelectedCallback(
- evt: EventTypes.InteractionEventType,
- annotation: HipDIAnnotation
- ): void {
- // 实现工具选中逻辑
- }
- /**
- * 处理鼠标拖拽
- */
- _dragCallback = (evt: EventTypes.InteractionEventType): void => {
- this.isDrawing = true;
- const eventDetail = evt.detail;
- const { element } = eventDetail;
- const enabledElement = getEnabledElement(element);
- if (!enabledElement || !this.editData) {
- return;
- }
- const { annotation, viewportIdsToRender } = this.editData;
- const { data } = annotation as HipDIAnnotation;
- if (annotation) {
- const { currentPoints } = eventDetail;
- const worldPos = currentPoints.world;
- const points = data.handles.points;
- const activeHandleIndex = data.handles.activeHandleIndex;
- if (activeHandleIndex !== null && activeHandleIndex < points.length) {
- points[activeHandleIndex] = worldPos;
- this._updateCachedStats(
- annotation as HipDIAnnotation,
- enabledElement
- );
- this.editData!.hasMoved = true;
- }
- utilities.triggerAnnotationRenderForViewportIds(
- viewportIdsToRender
- );
- }
- };
- /**
- * 处理鼠标抬起/点击
- */
- _endCallback = (evt: EventTypes.InteractionEventType): void => {
- const eventDetail = evt.detail;
- const { element } = eventDetail;
- if (!this.editData) {
- return;
- }
- const { annotation, hasMoved } = this.editData;
- const { data } = annotation as HipDIAnnotation;
- if (hasMoved) {
- this.editData.hasMoved = false;
- }
- };
- /**
- * 获取靠近图像点的手柄
- */
- getHandleNearImagePoint(
- element: HTMLDivElement,
- annotation: HipDIAnnotation,
- canvasCoords: CoreTypes.Point2,
- proximity: number
- ): Types.ToolHandle | undefined {
- const enabledElement = getEnabledElement(element);
- if (!enabledElement) {
- return undefined;
- }
- const { viewport } = enabledElement;
- const points = annotation.data.handles.points;
- const handleProximity = Math.max(proximity, 15);
- for (let i = 0; i < points.length; i++) {
- const point = points[i];
- const canvasPoint = viewport.worldToCanvas(point);
- const distance = Math.sqrt(
- Math.pow(canvasPoint[0] - canvasCoords[0], 2) +
- Math.pow(canvasPoint[1] - canvasCoords[1], 2)
- );
- if (distance < handleProximity) {
- annotation.data.handles.activeHandleIndex = i;
- return {
- worldPosition: point,
- } as Types.ToolHandle;
- }
- }
-
- annotation.data.handles.activeHandleIndex = null;
- return undefined;
- }
- /**
- * 更新缓存的统计数据
- */
- _updateCachedStats(
- annotation: HipDIAnnotation,
- enabledElement: CoreTypes.IEnabledElement
- ): void {
- const { viewport } = enabledElement;
- const { data } = annotation;
- const points = data.handles.points;
- const targetId = this.getTargetId(viewport);
- if (!targetId) {
- return;
- }
- if (!data.cachedStats) {
- data.cachedStats = {};
- }
- if (!data.cachedStats[targetId]) {
- data.cachedStats[targetId] = {
- distance: 0,
- DI: 0,
- };
- }
- const stats = data.cachedStats[targetId];
- if (points.length >= 6) {
- // 拟合髋臼圆(点1,2,3)
- const acetabulumCircle = fitCircleFrom3Points(
- points[0],
- points[1],
- points[2]
- );
- // 拟合股骨头圆(点4,5,6)
- const femurCircle = fitCircleFrom3Points(
- points[3],
- points[4],
- points[5]
- );
- if (!acetabulumCircle || !femurCircle) {
- console.warn('圆拟合失败,三点可能共线');
- return;
- }
- // 存储圆数据
- stats.acetabulumCircle = acetabulumCircle;
- stats.femurCircle = femurCircle;
- // 计算圆心距离d
- const M1 = acetabulumCircle.center;
- const M2 = femurCircle.center;
- const distance = Math.sqrt(
- Math.pow(M2[0] - M1[0], 2) +
- Math.pow(M2[1] - M1[1], 2) +
- Math.pow(M2[2] - M1[2], 2)
- );
- stats.distance = distance;
- // 计算DI指数
- const DI = distance / femurCircle.radius;
- stats.DI = DI;
- }
- }
- /**
- * 渲染注解
- */
- renderAnnotation = (
- enabledElement: CoreTypes.IEnabledElement,
- svgDrawingHelper: SVGDrawingHelper
- ): boolean => {
- let renderStatus = false;
- const { viewport } = enabledElement;
- const { element } = viewport;
- let annotations = annotation.state.getAnnotations(this.getToolName(), element);
- if (!annotations?.length) {
- return renderStatus;
- }
- for (let i = 0; i < annotations.length; i++) {
- const annotation = annotations[i] as HipDIAnnotation;
- const { annotationUID, data } = annotation;
- const points = data.handles.points;
- if (points.length < 1) {
- continue;
- }
- const targetId = this.getTargetId(viewport);
- const cachedStats = targetId ? data.cachedStats?.[targetId] : undefined;
- // 确定颜色(选中状态为蓝色,非选中为白色)
- const color = annotation.highlighted ? 'rgb(0, 0, 255)' : 'rgb(255, 255, 255)';
- // 转换所有点为 canvas 坐标
- const canvasPoints = points.map((p) => viewport.worldToCanvas(p));
- // 绘制髋臼圆
- if (cachedStats?.acetabulumCircle && annotationUID) {
- const center = cachedStats.acetabulumCircle.center;
- const centerCanvas = viewport.worldToCanvas(center);
- // 计算半径的像素值
- const radiusVector: Point3 = [cachedStats.acetabulumCircle.radius, 0, 0];
- const endPoint = vectorAdd(center, radiusVector);
- const endCanvas = viewport.worldToCanvas(endPoint);
- const radiusPixels = Math.sqrt(
- Math.pow(endCanvas[0] - centerCanvas[0], 2) +
- Math.pow(endCanvas[1] - centerCanvas[1], 2)
- );
- const circleUID = `${annotationUID}-acetabulum-circle`;
- drawCircleSvg(
- svgDrawingHelper,
- annotationUID,
- circleUID,
- centerCanvas,
- radiusPixels,
- {
- color: color,
- width: 2,
- }
- );
- }
- // 绘制股骨头圆
- if (cachedStats?.femurCircle && annotationUID) {
- const center = cachedStats.femurCircle.center;
- const centerCanvas = viewport.worldToCanvas(center);
- // 计算半径的像素值
- const radiusVector: Point3 = [cachedStats.femurCircle.radius, 0, 0];
- const endPoint = vectorAdd(center, radiusVector);
- const endCanvas = viewport.worldToCanvas(endPoint);
- const radiusPixels = Math.sqrt(
- Math.pow(endCanvas[0] - centerCanvas[0], 2) +
- Math.pow(endCanvas[1] - centerCanvas[1], 2)
- );
- const circleUID = `${annotationUID}-femur-circle`;
- drawCircleSvg(
- svgDrawingHelper,
- annotationUID,
- circleUID,
- centerCanvas,
- radiusPixels,
- {
- color: color,
- width: 2,
- }
- );
- }
- // 绘制圆心连线
- if (cachedStats?.acetabulumCircle && cachedStats?.femurCircle && annotationUID) {
- const M1 = cachedStats.acetabulumCircle.center;
- const M2 = cachedStats.femurCircle.center;
- const M1Canvas = viewport.worldToCanvas(M1);
- const M2Canvas = viewport.worldToCanvas(M2);
- const lineUID = `${annotationUID}-center-line`;
- drawLineSvg(
- svgDrawingHelper,
- annotationUID,
- lineUID,
- M1Canvas,
- M2Canvas,
- {
- color: color,
- width: 2,
- }
- );
- }
- // 绘制6个控制点
- if (annotationUID) {
- const handleGroupUID = '0';
- // 根据工具选中状态调整手柄半径:选中时为12,否则为6
- const isSelected = annotation.isSelected || annotation.highlighted;
- const handleRadius = isSelected ? 12 : 6;
- drawHandles(
- svgDrawingHelper,
- annotationUID,
- handleGroupUID,
- canvasPoints,
- {
- color: 'rgb(255, 255, 255)',
- handleRadius: handleRadius,
- }
- );
- }
- // 绘制DI数值标注(黄色,可拖拽)
- if (cachedStats?.femurCircle && cachedStats.DI !== undefined && annotationUID) {
- const femurCenterCanvas = viewport.worldToCanvas(cachedStats.femurCircle.center);
- const textLines = [`DI: ${cachedStats.DI.toFixed(2)}`];
- const textUID = `${annotationUID}-DI-text`;
- const textBoxPosition: CoreTypes.Point2 = data.textBox || [
- femurCenterCanvas[0] + 20,
- femurCenterCanvas[1] - 20,
- ];
- drawLinkedTextBox(
- svgDrawingHelper,
- annotationUID,
- textUID,
- textLines,
- textBoxPosition,
- [femurCenterCanvas],
- {},
- {
- color: 'rgb(255, 255, 0)', // 黄色
- }
- );
- }
- renderStatus = true;
- }
- return renderStatus;
- };
- }
|