ExcalidrawView.vue 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <template>
  2. <div ref="canvasContainer" class="excalidraw-wrapper" @click="showCanvasTop" />
  3. <div ref="canvasFloating" v-if="showFullView" class="floating-canvas" @mousedown="onMouseDown" @wheel.prevent="onWheel" @click="onCloseFloating" />
  4. </template>
  5. <script setup lang="ts">
  6. import { onMounted, ref, nextTick, onUnmounted } from 'vue'
  7. import { withBase } from 'vitepress';
  8. import { exportToCanvas } from '@excalidraw/excalidraw'
  9. import { ExportedDataState } from '@excalidraw/excalidraw/data/types'
  10. interface Props {
  11. filePath: string;
  12. }
  13. const props = defineProps<Props>()
  14. const canvasContainer = ref<HTMLCanvasElement | null>(null)
  15. const canvasFloating = ref<HTMLCanvasElement | null>(null)
  16. const showFullView = ref(false);
  17. let excalidrawJson: ExportedDataState | undefined = undefined
  18. let topCanvas: HTMLCanvasElement | undefined = undefined
  19. let clickTimer: ReturnType<typeof setTimeout> | null = null;
  20. let scale = 1;
  21. let origin = { x: 0, y: 0 };
  22. let lastMouse = { x: 0, y: 0 };
  23. let dragging = false;
  24. let hasMoved = false; // 标记是否拖动过
  25. const dblclickCanvasHandler = (e: MouseEvent) => {
  26. if (clickTimer) {
  27. clearTimeout(clickTimer); // 阻止 click 事件
  28. clickTimer = null;
  29. }
  30. origin = { x: 0, y: 0 };
  31. scale = 1;
  32. updateTransform();
  33. };
  34. function showCanvasTop() {
  35. showFullView.value = true;
  36. // 等待 DOM 渲染后复制内容
  37. nextTick(async () => {
  38. if (canvasFloating.value && excalidrawJson) {
  39. const canvas = await drawCanvas(excalidrawJson)
  40. if (canvas) {
  41. topCanvas = canvas
  42. canvas.style.transform = `translate(0px, 0px) scale(1)`;
  43. origin = { x: 0, y: 0 };
  44. scale = 1;
  45. canvasFloating.value.appendChild(canvas)
  46. // 双击重置
  47. canvas.addEventListener('dblclick', dblclickCanvasHandler);
  48. }
  49. }
  50. });
  51. }
  52. function closeFullView() {
  53. showFullView.value = false;
  54. if (topCanvas) {
  55. topCanvas.removeEventListener('dblclick', dblclickCanvasHandler);
  56. }
  57. if (canvasFloating.value) {
  58. canvasFloating.value.innerHTML = ''; // 清空 canvas
  59. }
  60. }
  61. function onCloseFloating(e: MouseEvent) {
  62. if (clickTimer) clearTimeout(clickTimer);
  63. clickTimer = setTimeout(() => {
  64. // 这是单击
  65. if (hasMoved) {
  66. hasMoved = false;
  67. return; // 用户拖动过,不关闭
  68. }
  69. closeFullView()
  70. }, 500); // 等待双击事件,如果没有才执行
  71. }
  72. function onMouseDown(e: MouseEvent) {
  73. // 如果按的是 canvas,就拖动
  74. if (topCanvas && topCanvas.contains(e.target as Node)) {
  75. dragging = true;
  76. hasMoved = false; // 重置状态
  77. lastMouse = { x: e.clientX, y: e.clientY };
  78. const onMouseMove = (e: MouseEvent) => {
  79. if (!dragging) return;
  80. const dx = e.clientX - lastMouse.x;
  81. const dy = e.clientY - lastMouse.y;
  82. // 如果移动距离大于阈值,认为已经拖动过
  83. if (Math.abs(dx) > 2 || Math.abs(dy) > 2) {
  84. hasMoved = true;
  85. }
  86. origin.x += dx;
  87. origin.y += dy;
  88. lastMouse = { x: e.clientX, y: e.clientY };
  89. updateTransform();
  90. };
  91. const onMouseUp = () => {
  92. dragging = false;
  93. window.removeEventListener('mousemove', onMouseMove);
  94. window.removeEventListener('mouseup', onMouseUp);
  95. };
  96. // 添加鼠标事件监控
  97. window.addEventListener('mousemove', onMouseMove);
  98. window.addEventListener('mouseup', onMouseUp);
  99. }
  100. }
  101. function updateTransform() {
  102. if (topCanvas) {
  103. topCanvas.style.transform = `translate(${origin.x}px, ${origin.y}px) scale(${scale})`;
  104. }
  105. }
  106. function onWheel(e: WheelEvent) {
  107. const delta = -e.deltaY;
  108. const factor = delta > 0 ? 1.1 : 0.9;
  109. scale *= factor;
  110. scale = Math.min(Math.max(0.2, scale), 10); // 限制缩放范围
  111. updateTransform();
  112. }
  113. const getExcalidraw = async (path: string): Promise<ExportedDataState | undefined> => {
  114. const res = await fetch(withBase(path)).catch((err) => {
  115. console.log("excalidraw file err: ", err)
  116. })
  117. if (!res) return undefined
  118. const json = await res.json()
  119. return json
  120. }
  121. const drawCanvas = async (data: ExportedDataState, width?: number, height?: number): Promise<HTMLCanvasElement> => {
  122. // const maxWidthOrHeight = width > height ? height : width
  123. // 改为只限制宽度,因为渲染前父窗口高度可能为0,导致maxWidthOrHeight不生效
  124. const maxWidthOrHeight = width
  125. const canvas = await exportToCanvas({
  126. ...data,
  127. maxWidthOrHeight,// 绘制的最大高度或宽度,设置maxWidthOrHeight后getDimensions则不生效
  128. // getDimensions: (width: number, height: number) => {
  129. // return {
  130. // width,
  131. // height,
  132. // scale: 1
  133. // }
  134. // }, // 参数为原始绘制尺寸,返回尺寸和比例 {width: number; height: number; scale: number}
  135. exportPadding: 10 // 添加边距,默认10
  136. })
  137. return canvas
  138. }
  139. function onKeyDown(e: KeyboardEvent) {
  140. if (e.key === 'Escape') {
  141. closeFullView()
  142. }
  143. }
  144. onMounted(async () => {
  145. console.log("excalidrawJson: ", props.filePath)
  146. excalidrawJson = await getExcalidraw(props.filePath)
  147. if (excalidrawJson && canvasContainer.value) {
  148. let excalidrawCanvas = await drawCanvas(excalidrawJson, canvasContainer.value.clientWidth, canvasContainer.value.clientHeight)
  149. if (excalidrawCanvas) {
  150. canvasContainer.value.appendChild(excalidrawCanvas)
  151. }
  152. // 使用 ResizeObserver 监听父容器宽度变化
  153. const resizeObserver = new ResizeObserver(async (entries: ResizeObserverEntry[]) => {
  154. for (const entry of entries) {
  155. const el = entry.target
  156. if (el === canvasContainer.value && excalidrawJson) {
  157. excalidrawCanvas = await drawCanvas(excalidrawJson, el.clientWidth, el.clientHeight)
  158. }
  159. }
  160. });
  161. resizeObserver.observe(canvasContainer.value!);
  162. }
  163. window.addEventListener('keydown', onKeyDown);
  164. })
  165. onUnmounted(() => {
  166. window.removeEventListener('keydown', onKeyDown);
  167. })
  168. </script>
  169. <style scoped>
  170. .excalidraw-wrapper {
  171. width: 100%;
  172. border: 1px solid #ddd;
  173. }
  174. .floating-canvas {
  175. position: fixed;
  176. top: 0;
  177. left: 0;
  178. width: 100vw;
  179. height: 100vh;
  180. background: rgba(0, 0, 0, 0.8);
  181. z-index: 9999;
  182. display: flex;
  183. justify-content: center;
  184. align-items: center;
  185. overflow: hidden;
  186. cursor: grab;
  187. }
  188. .floating-canvas:active {
  189. cursor: grabbing;
  190. }
  191. .floating-canvas canvas {
  192. /* max-width: 90vw; */
  193. max-width: none;
  194. /* max-height: 90vh; */
  195. max-height: none;
  196. box-shadow: 0 0 12px #fff;
  197. transition: transform 0.05s;
  198. }
  199. </style>