fabricRuler.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. import { Keybinding } from './keybinding'
  2. import { Disposable } from '@/utils/lifecycle'
  3. import { computed, watchEffect } from 'vue'
  4. // import { useThemes } from '@/hooks/useThemes'
  5. import { DesignUnitMode } from '@/configs/background'
  6. import { PiBy180, isMobile } from '@/utils/common'
  7. import { TAxis, Point, Rect as fabricRect, Object as FabricObject, TPointerEventInfo, TPointerEvent } from 'fabric'
  8. import { useMainStore, useTemplatesStore } from '@/store'
  9. import { storeToRefs } from 'pinia'
  10. import { px2mm } from '@/utils/image'
  11. import { ElementNames } from '@/types/elements'
  12. import { FabricCanvas } from './fabricCanvas'
  13. import { ReferenceLine } from '@/extension/object/ReferenceLine'
  14. import { WorkSpaceDrawType } from '@/configs/canvas'
  15. type Rect = { left: number; top: number; width: number; height: number }
  16. /**
  17. * 配置
  18. */
  19. export interface RulerOptions {
  20. /**
  21. * 标尺宽高
  22. * @default 10
  23. */
  24. ruleSize?: number
  25. /**
  26. * 字体大小
  27. * @default 10
  28. */
  29. fontSize?: number
  30. /**
  31. * 是否开启标尺
  32. * @default false
  33. */
  34. enabled?: boolean
  35. /**
  36. * 背景颜色
  37. */
  38. backgroundColor?: string
  39. /**
  40. * 文字颜色
  41. */
  42. textColor?: string
  43. /**
  44. * 边框颜色
  45. */
  46. borderColor?: string
  47. /**
  48. * 高亮颜色
  49. */
  50. highlightColor?: string
  51. /**
  52. * 高亮颜色
  53. */
  54. unitName: string
  55. }
  56. export type HighlightRect = {skip?: TAxis} & Rect
  57. export class FabricRuler extends Disposable {
  58. private canvasEvents
  59. public lastCursor: string
  60. public workSpaceDraw?: fabricRect
  61. public options: Required<RulerOptions>
  62. public tempReferenceLine?: ReferenceLine
  63. private activeOn: string = "up"
  64. private objectRect: undefined | {
  65. x: HighlightRect[],
  66. y: HighlightRect[]
  67. }
  68. constructor(private readonly canvas: FabricCanvas) {
  69. super()
  70. this.lastCursor = this.canvas.defaultCursor
  71. // 合并默认配置
  72. this.options = Object.assign({
  73. ruleSize: 20,
  74. fontSize: 8,
  75. enabled: isMobile() ? false : true,
  76. })
  77. // const { isDark } = useThemes()
  78. const isDark = false
  79. const { unitMode } = storeToRefs(useMainStore())
  80. watchEffect(() => {
  81. const unitName = DesignUnitMode.filter(ele => ele.id === unitMode.value)[0].name
  82. this.options = {
  83. ...this.options,
  84. ...(isDark
  85. ? {
  86. backgroundColor: '#242424',
  87. borderColor: '#555',
  88. highlightColor: '#165dff3b',
  89. textColor: '#ddd',
  90. unitName: unitName,
  91. }
  92. : {
  93. backgroundColor: '#fff',
  94. borderColor: '#ccc',
  95. highlightColor: '#165dff3b',
  96. textColor: '#444',
  97. unitName: unitName,
  98. }),
  99. }
  100. this.render({ ctx: this.canvas.contextContainer })
  101. })
  102. this.canvasEvents = {
  103. 'after:render': this.render.bind(this),
  104. 'mouse:move': this.mouseMove.bind(this),
  105. 'mouse:down': this.mouseDown.bind(this),
  106. 'mouse:up': this.mouseUp.bind(this),
  107. 'referenceline:moving': this.referenceLineMoving.bind(this),
  108. 'referenceline:mouseup': this.referenceLineMouseup.bind(this),
  109. }
  110. this.enabled = this.options.enabled
  111. canvas.ruler = this
  112. }
  113. public getPointHover(point: Point): 'vertical' | 'horizontal' | '' {
  114. if (
  115. new fabricRect({
  116. left: 0,
  117. top: 0,
  118. width: this.options.ruleSize,
  119. height: this.canvas.height,
  120. absolutePositioned: true,
  121. }).containsPoint(point)
  122. ) {
  123. return 'vertical';
  124. } else if (
  125. new fabricRect({
  126. left: 0,
  127. top: 0,
  128. width: this.canvas.width,
  129. height: this.options.ruleSize,
  130. absolutePositioned: true,
  131. }).containsPoint(point)
  132. ) {
  133. return 'horizontal';
  134. }
  135. return '';
  136. }
  137. private mouseMove(e: TPointerEventInfo<TPointerEvent>) {
  138. if (!e.viewportPoint) return
  139. if (this.tempReferenceLine && e.scenePoint) {
  140. const pos: Partial<ReferenceLine> = {};
  141. if (this.tempReferenceLine.axis === 'horizontal') {
  142. pos.top = e.scenePoint.y;
  143. }
  144. else {
  145. pos.left = e.scenePoint.x;
  146. }
  147. this.tempReferenceLine.set({ ...pos, visible: true });
  148. this.canvas.renderAll();
  149. const event = this.getCommonEventInfo(e) as any;
  150. this.canvas.fire('object:moving', event);
  151. this.tempReferenceLine.fire('moving', event);
  152. }
  153. const status = this.getPointHover(e.viewportPoint)
  154. this.canvas.defaultCursor = this.lastCursor
  155. if (!status) return
  156. this.lastCursor = this.canvas.defaultCursor
  157. this.canvas.defaultCursor = status === 'horizontal' ? 'ns-resize' : 'ew-resize';
  158. }
  159. private mouseDown(e: TPointerEventInfo<TPointerEvent>) {
  160. const pointHover = this.getPointHover(e.viewportPoint)
  161. if (!pointHover) return
  162. if (this.activeOn === 'up') {
  163. this.canvas.selection = false
  164. this.activeOn = 'down'
  165. const point = pointHover === 'horizontal' ? e.viewportPoint.y : e.viewportPoint.x
  166. this.tempReferenceLine = new ReferenceLine(
  167. point,
  168. {
  169. type: 'ReferenceLine',
  170. axis: pointHover,
  171. visible: false,
  172. name: 'ReferenceLine',
  173. hasControls: false,
  174. hasBorders: false,
  175. stroke: 'pink',
  176. fill: 'pink',
  177. originX: 'center',
  178. originY: 'center',
  179. padding: 4,
  180. globalCompositeOperation: 'difference',
  181. }
  182. );
  183. this.canvas.add(this.tempReferenceLine)
  184. const templatesStore = useTemplatesStore()
  185. templatesStore.addElement(this.tempReferenceLine)
  186. this.canvas.setActiveObject(this.tempReferenceLine)
  187. this.canvas._setupCurrentTransform(e.e, this.tempReferenceLine, true)
  188. this.tempReferenceLine.fire('down', this.getCommonEventInfo(e));
  189. }
  190. }
  191. private getCommonEventInfo(e: TPointerEventInfo<TPointerEvent>) {
  192. if (!this.tempReferenceLine || !e.scenePoint) return;
  193. return {
  194. e: e.e,
  195. transform: this.tempReferenceLine.get('transform'),
  196. pointer: {
  197. x: e.scenePoint.x,
  198. y: e.scenePoint.y,
  199. },
  200. target: this.tempReferenceLine,
  201. };
  202. }
  203. private mouseUp(e: TPointerEventInfo<TPointerEvent>) {
  204. if (this.activeOn !== 'down') return;
  205. this.canvas.selection = true
  206. this.tempReferenceLine!.selectable = false
  207. this.canvas.renderAll()
  208. this.activeOn = 'up';
  209. // @ts-ignore
  210. this.tempReferenceLine?.fire('up', this.getCommonEventInfo(e));
  211. this.tempReferenceLine = undefined;
  212. }
  213. public setWorkSpaceDraw() {
  214. this.workSpaceDraw = this.canvas.getObjects().filter(item => item.id === WorkSpaceDrawType)[0] as fabricRect
  215. }
  216. public isRectOut(object: FabricObject, target: ReferenceLine): boolean {
  217. // const { top, height, left, width } = object;
  218. // if (top === undefined || height === undefined || left === undefined || width === undefined) {
  219. // return false;
  220. // }
  221. // const targetRect = target.getBoundingRect(true, true);
  222. // const {
  223. // top: targetTop,
  224. // height: targetHeight,
  225. // left: targetLeft,
  226. // width: targetWidth,
  227. // } = targetRect;
  228. // if (target.isHorizontal() && (top > targetTop + 1 || top + height < targetTop + targetHeight - 1)) {
  229. // return true;
  230. // }
  231. // else if (!target.isHorizontal() && (left > targetLeft + 1 || left + width < targetLeft + targetWidth - 1)) {
  232. // return true;
  233. // }
  234. return false;
  235. };
  236. referenceLineMoving(e: any) {
  237. if (!this.workSpaceDraw) {
  238. this.setWorkSpaceDraw();
  239. return;
  240. }
  241. const { target } = e;
  242. if (this.isRectOut(this.workSpaceDraw, target)) {
  243. target.moveCursor = 'not-allowed';
  244. }
  245. }
  246. referenceLineMouseup(e: any) {
  247. if (!this.workSpaceDraw) {
  248. this.setWorkSpaceDraw();
  249. return;
  250. }
  251. const { target } = e;
  252. if (this.isRectOut(this.workSpaceDraw, target)) {
  253. this.canvas.remove(target);
  254. this.canvas.setCursor(this.canvas.defaultCursor ?? '');
  255. }
  256. }
  257. public get enabled() {
  258. return this.options.enabled
  259. }
  260. public set enabled(value) {
  261. this.options.enabled = value
  262. if (value) {
  263. this.canvas.on(this.canvasEvents)
  264. this.render({ ctx: this.canvas.contextContainer })
  265. }
  266. else {
  267. this.canvas.off(this.canvasEvents)
  268. this.canvas.requestRenderAll()
  269. }
  270. }
  271. /**
  272. * 获取画板尺寸
  273. */
  274. private getSize() {
  275. return {
  276. width: this.canvas.width,
  277. height: this.canvas.height,
  278. }
  279. }
  280. private render({ ctx }: { ctx: CanvasRenderingContext2D }) {
  281. if (ctx !== this.canvas.contextContainer) return
  282. const { viewportTransform: vpt } = this.canvas
  283. // 计算元素矩形
  284. this.calcObjectRect()
  285. // 绘制尺子
  286. this.draw({
  287. ctx,
  288. isHorizontal: true,
  289. rulerLength: this.getSize().width,
  290. startCalibration: -(vpt[4] / vpt[0]),
  291. })
  292. this.draw({
  293. ctx,
  294. isHorizontal: false,
  295. rulerLength: this.getSize().height,
  296. startCalibration: -(vpt[5] / vpt[3]),
  297. })
  298. const { borderColor, backgroundColor, ruleSize, textColor } = this.options
  299. this.darwRect(ctx, {
  300. left: 0,
  301. top: 0,
  302. width: ruleSize,
  303. height: ruleSize,
  304. fill: backgroundColor,
  305. stroke: borderColor,
  306. })
  307. this.darwText(ctx, {
  308. text: this.options.unitName,
  309. left: ruleSize / 2,
  310. top: ruleSize / 2,
  311. align: 'center',
  312. baseline: 'middle',
  313. fill: textColor,
  314. })
  315. }
  316. private draw(opt: {ctx: CanvasRenderingContext2D, isHorizontal: boolean, rulerLength: number, startCalibration: number}) {
  317. const { ctx, isHorizontal, rulerLength, startCalibration } = opt
  318. const zoom = this.canvas.getZoom()
  319. const gap = this.getGap(zoom)
  320. const unitLength = Math.ceil(rulerLength / zoom)
  321. const startValue = Math.floor(startCalibration / gap) * gap
  322. const startOffset = startValue - startCalibration
  323. const canvasSize = this.getSize()
  324. const { textColor, borderColor, ruleSize, highlightColor } = this.options
  325. // 文字顶部偏移
  326. const padding = 2.5
  327. // 背景
  328. this.darwRect(ctx, {
  329. left: 0,
  330. top: 0,
  331. width: isHorizontal ? canvasSize.width : ruleSize,
  332. height: isHorizontal ? ruleSize : canvasSize.height,
  333. fill: this.options.backgroundColor,
  334. stroke: this.options.borderColor,
  335. })
  336. // 标尺刻度线显示
  337. for (let pos = 0; pos + startOffset <= unitLength; pos += gap) {
  338. for (let index = 0; index < 10; index++) {
  339. const position = Math.round((startOffset + pos + (gap * index) / 10) * zoom)
  340. const isMajorLine = index === 0
  341. const [left, top] = isHorizontal ? [position, isMajorLine ? 0 : ruleSize - 8] : [isMajorLine ? 0 : ruleSize - 8, position]
  342. const [width, height] = isHorizontal ? [0, ruleSize - top] : [ruleSize - left, 0]
  343. this.darwLine(ctx, {
  344. left,
  345. top,
  346. width,
  347. height,
  348. stroke: borderColor,
  349. })
  350. }
  351. }
  352. // 标尺蓝色遮罩
  353. if (this.objectRect) {
  354. const axis = isHorizontal ? 'x' : 'y'
  355. this.objectRect[axis].forEach((rect) => {
  356. // 跳过指定矩形
  357. if (rect.skip === axis) return
  358. const [left, top, width, height] = isHorizontal ? [(rect.left - startCalibration) * zoom, 0, rect.width * zoom, ruleSize] : [0, (rect.top - startCalibration) * zoom, ruleSize, rect.height * zoom]
  359. // 高亮遮罩
  360. // ctx.save()
  361. this.darwRect(ctx, {
  362. left,
  363. top,
  364. width,
  365. height,
  366. fill: highlightColor,
  367. })
  368. // ctx.restore()
  369. })
  370. }
  371. // 标尺文字显示
  372. for (let pos = 0; pos + startOffset <= unitLength; pos += gap) {
  373. const position = (startOffset + pos) * zoom
  374. let textValue = (startValue + pos).toString()
  375. if (this.options.unitName === 'mm') {
  376. textValue = px2mm(startValue + pos).toFixed(0)
  377. }
  378. const [left, top, angle] = isHorizontal ? [position + 6, padding, 0] : [padding, position - 6, -90]
  379. this.darwText(ctx, {
  380. text: textValue,
  381. left,
  382. top,
  383. fill: textColor,
  384. angle,
  385. })
  386. }
  387. // draw end
  388. }
  389. private getGap(zoom: number) {
  390. const zooms = [0.02, 0.03, 0.05, 0.1, 0.2, 0.5, 1, 2, 5]
  391. const gaps = [5000, 2500, 1000, 500, 200, 100, 50, 20, 10]
  392. let i = 0
  393. while (i < zooms.length && zooms[i] < zoom) {
  394. i++
  395. }
  396. return gaps[i - 1] || 10000
  397. }
  398. private darwRect(
  399. ctx: CanvasRenderingContext2D,
  400. {
  401. left,
  402. top,
  403. width,
  404. height,
  405. fill,
  406. stroke,
  407. strokeWidth,
  408. }: {
  409. left: number
  410. top: number
  411. width: number
  412. height: number
  413. fill?: string | CanvasGradient | CanvasPattern
  414. stroke?: string
  415. strokeWidth?: number
  416. },
  417. ) {
  418. ctx.save()
  419. ctx.beginPath()
  420. fill && (ctx.fillStyle = fill)
  421. ctx.rect(left, top, width, height)
  422. ctx.fill()
  423. if (stroke) {
  424. ctx.strokeStyle = stroke
  425. ctx.lineWidth = strokeWidth ?? 1
  426. ctx.stroke()
  427. }
  428. ctx.restore()
  429. }
  430. private darwText(
  431. ctx: CanvasRenderingContext2D,
  432. {
  433. left,
  434. top,
  435. text,
  436. fill,
  437. align,
  438. angle,
  439. fontSize,
  440. baseline,
  441. }: {
  442. left: number
  443. top: number
  444. text: string
  445. fill?: string | CanvasGradient | CanvasPattern
  446. align?: CanvasTextAlign
  447. baseline?: CanvasTextBaseline
  448. angle?: number
  449. fontSize?: number
  450. },
  451. ) {
  452. ctx.save()
  453. fill && (ctx.fillStyle = fill)
  454. ctx.textAlign = align ?? 'left'
  455. ctx.textBaseline = baseline ?? 'top'
  456. ctx.font = `${fontSize ?? 12}px Helvetica`
  457. if (angle) {
  458. ctx.translate(left, top)
  459. ctx.rotate(PiBy180 * angle)
  460. ctx.translate(-left, -top)
  461. }
  462. ctx.fillText(text, left, top)
  463. ctx.restore()
  464. }
  465. private darwLine(
  466. ctx: CanvasRenderingContext2D,
  467. {
  468. left,
  469. top,
  470. width,
  471. height,
  472. stroke,
  473. lineWidth,
  474. }: {
  475. left: number
  476. top: number
  477. width: number
  478. height: number
  479. stroke?: string | CanvasGradient | CanvasPattern
  480. lineWidth?: number
  481. },
  482. ) {
  483. ctx.save()
  484. ctx.beginPath()
  485. stroke && (ctx.strokeStyle = stroke)
  486. ctx.lineWidth = lineWidth ?? 1
  487. ctx.moveTo(left, top)
  488. ctx.lineTo(left + width, top + height)
  489. ctx.stroke()
  490. ctx.restore()
  491. }
  492. private calcObjectRect() {
  493. const activeObjects = this.canvas.getActiveObjects()
  494. if (activeObjects.length === 0) {
  495. this.objectRect = undefined
  496. return
  497. }
  498. if (activeObjects[0].name.toLowerCase() === ElementNames.REFERENCELINE) {
  499. this.objectRect = undefined
  500. return
  501. }
  502. const allRect = activeObjects.reduce((rects, obj) => {
  503. const rect: HighlightRect = obj.getBoundingRect()
  504. rects.push(rect)
  505. return rects
  506. }, [] as HighlightRect[])
  507. if (allRect.length === 0) return
  508. this.objectRect = {
  509. x: this.mergeLines(allRect, true),
  510. y: this.mergeLines(allRect, false),
  511. }
  512. }
  513. private mergeLines(rect: Rect[], isHorizontal: boolean) {
  514. const axis = isHorizontal ? 'left' : 'top'
  515. const length = isHorizontal ? 'width' : 'height'
  516. // 先按照 axis 的大小排序
  517. rect.sort((a, b) => a[axis] - b[axis])
  518. const mergedLines = []
  519. let currentLine = Object.assign({}, rect[0])
  520. for (let i = 1; i < rect.length; i++) {
  521. const line = Object.assign({}, rect[i])
  522. if (currentLine[axis] + currentLine[length] >= line[axis]) {
  523. // 当前线段和下一个线段相交,合并宽度
  524. currentLine[length] =
  525. Math.max(currentLine[axis] + currentLine[length], line[axis] + line[length]) -
  526. currentLine[axis]
  527. } else {
  528. // 当前线段和下一个线段不相交,将当前线段加入结果数组中,并更新当前线段为下一个线段
  529. mergedLines.push(currentLine)
  530. currentLine = Object.assign({}, line)
  531. }
  532. }
  533. // 加入数组
  534. mergedLines.push(currentLine)
  535. return mergedLines
  536. }
  537. public dispose(): void {
  538. super.dispose()
  539. this.enabled = false
  540. }
  541. }