@logicflow/extension 2.0.0-beta.3 → 2.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/.turbo/turbo-build.log +6 -6
  2. package/dist/index.min.js +2 -2
  3. package/es/components/menu/index.d.ts +1 -1
  4. package/es/components/menu/index.js +9 -10
  5. package/es/components/menu/index.js.map +1 -1
  6. package/es/index.d.ts +1 -0
  7. package/es/index.js +1 -0
  8. package/es/index.js.map +1 -1
  9. package/es/materials/node-selection/index.d.ts +2 -1
  10. package/es/materials/node-selection/index.js +64 -56
  11. package/es/materials/node-selection/index.js.map +1 -1
  12. package/es/tools/snapshot/index.d.ts +107 -11
  13. package/es/tools/snapshot/index.js +368 -149
  14. package/es/tools/snapshot/index.js.map +1 -1
  15. package/es/tools/snapshot/utils.d.ts +35 -0
  16. package/es/tools/snapshot/utils.js +238 -0
  17. package/es/tools/snapshot/utils.js.map +1 -0
  18. package/lib/components/menu/index.d.ts +1 -1
  19. package/lib/components/menu/index.js +9 -10
  20. package/lib/components/menu/index.js.map +1 -1
  21. package/lib/index.d.ts +1 -0
  22. package/lib/index.js +1 -0
  23. package/lib/index.js.map +1 -1
  24. package/lib/materials/node-selection/index.d.ts +2 -1
  25. package/lib/materials/node-selection/index.js +63 -55
  26. package/lib/materials/node-selection/index.js.map +1 -1
  27. package/lib/tools/snapshot/index.d.ts +107 -11
  28. package/lib/tools/snapshot/index.js +368 -149
  29. package/lib/tools/snapshot/index.js.map +1 -1
  30. package/lib/tools/snapshot/utils.d.ts +35 -0
  31. package/lib/tools/snapshot/utils.js +247 -0
  32. package/lib/tools/snapshot/utils.js.map +1 -0
  33. package/package.json +3 -3
  34. package/rollup.config.js +1 -1
  35. package/src/components/menu/index.ts +16 -13
  36. package/src/index.ts +1 -0
  37. package/src/materials/node-selection/index.ts +72 -69
  38. package/src/tools/snapshot/README.md +130 -5
  39. package/src/tools/snapshot/index.ts +290 -101
  40. package/src/tools/snapshot/utils.ts +163 -0
@@ -1,9 +1,134 @@
1
- ## 截取logic-flow内部图形保存为文件并下载
1
+ # 导出 Snapshot
2
2
 
3
- ## 往logicflow上下文中添加api getSnapshot
3
+ 我们经常需要将画布内容通过图片的形式导出来,我们提供了一个独立的插件包 `Snapshot` 来使用这个功能。
4
4
 
5
- ```ts
5
+ ## 使用
6
+
7
+ ### 1. 注册
8
+
9
+ 两种注册方式,全局注册和局部注册,区别是全局注册每一个`lf`实例都可以使用。
10
+
11
+ ```tsx | pure
12
+ import LogicFlow from "@logicflow/core";
13
+ import { Snapshot } from "@logicflow/extension";
14
+
15
+ // 全局注册
6
16
  LogicFlow.use(Snapshot);
7
- const lf = new LogicFlow({});
8
- lf.getSnapshot();
17
+
18
+ // 局部注册
19
+ const lf = new LogicFlow({
20
+ ...config,
21
+ plugins: [Snapshot]
22
+ });
23
+
24
+ ```
25
+
26
+ ### 2. 使用
27
+
28
+ 注册后,`lf`实例身上将被挂载`getSnapshot()`方法,通过`lf.getSnapshot()`方法调用。
29
+
30
+ ```tsx | pure
31
+
32
+ // 可以使用任意方式触发,然后将绘制的图形下载到本地磁盘上
33
+ document.getElementById("button").addEventListener("click", () => {
34
+ lf.getSnapshot();
35
+
36
+ // 或者 1.1.13版本
37
+ // lf.extension.snapshot.getSnapshot()
38
+ });
39
+
9
40
  ```
41
+
42
+ 值得一提的是:通过此插件截取下载的图片不会因为偏移、缩放受到影响。
43
+
44
+ ## 自定义设置 css
45
+
46
+ 当自定义元素在导出图片时需要额外添加 css 样式时,可以用如下方式实现:
47
+
48
+ 为了保持流程图生成的图片与画布上效果一致,`snapshot`插件默认会将当前页面所有的 `css` 规则都加载到导出图片中, 但是可能会因为 css 文件跨域引起报错,参考 issue575。可以修改useGlobalRules来禁止加载所有 css 规则,然后通过`customCssRules`属性来自定义增加css样式。
49
+
50
+ ```tsx
51
+
52
+ // 默认开启css样式
53
+ lf.extension.snapshot.useGlobalRules = true
54
+ // 不会覆盖css样式,会叠加,customCssRules优先级高
55
+ lf.extension.snapshot.customCssRules = `
56
+ .uml-wrapper {
57
+ line-height: 1.2;
58
+ text-align: center;
59
+ color: blue;
60
+ }
61
+ `
62
+
63
+ ```
64
+
65
+ ## API
66
+
67
+ ### lf.getSnapshot(...)
68
+
69
+ 导出图片。
70
+
71
+ ```ts
72
+
73
+ getSnapshot(fileName?: string, toImageOptions?: ToImageOptions) : Promise<void>
74
+
75
+ ```
76
+
77
+ `fileName` 为文件名称,不填为默认为`logic-flow.当前时间戳`,`ToImageOptions` 描述如下:
78
+
79
+ | 属性名 | 类型 | 默认值 | 必填 | 描述 |
80
+ | --------- | -------- | -------------------------- | -------- | ----------------------------------------------------------------- |
81
+ | fileType | string | png | | 图片类型: 默认不填是png 还可以设置有webp、gif、jpeg、svg |
82
+ | width | number | - | | 自定义导出图片的宽度,不设置即可,设置可能会拉伸图形 |
83
+ | height | numebr | - | | 自定义导出图片的宽度,不设置即可,设置可能会拉伸图形 |
84
+ | backgroundColor | string | - | | 图片背景,不设置背景默认透明 |
85
+ | quality | number | - | | 图片质量,在指定图片格式为 jpeg 或 webp 的情况下,可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围,将会使用默认值 0.92。其他不合法参数会被忽略 |
86
+ | padding | number | 40 | | 图片内边距: 元素内容所在区之外空白空间,不设置默认有40的内边距 |
87
+ | partial | boolean | - | | 导出时是否开启局部渲染,false:将导出画布上所有的元素,true:只导出画面区域内的可见元素,不设置默认为lf实例身上partial值 |
88
+
89
+ 注意:
90
+ - `svg`目前暂不支持`width`,`height`, `backgroundColor`, `padding` 属性。
91
+ - 自定义宽高后,可能会拉伸图形,这时候`padding`也会被拉伸导致不准确。
92
+
93
+ ### lf.getSnapshotBlob(...)
94
+
95
+ `snapshot` 除了支持图片类型导出,还支持下载<a href="https://developer.mozilla.org/zh-CN/docs/Web/API/Blob" target="_blank"> Blob文件对象 </a> 和 <a href="https://developer.mozilla.org/zh-CN/docs/Glossary/Base64" target="_blank"> Base64文本编码 </a>
96
+
97
+ 获取`Blob`对象。
98
+
99
+ ```ts
100
+
101
+ async getSnapshotBlob(backgroundColor?: string, fileType?: string) : Promise<SnapshotResponse>
102
+
103
+ // example
104
+ const { data : blob } = await lf.getSnapshotBlob()
105
+ console.log(blob)
106
+
107
+ ```
108
+ `backgroundColor`: 背景,不填默认为透明。
109
+
110
+ `fileType`: 文件类型,不填默认为png。
111
+
112
+ `SnapshotResponse`: 返回对象。
113
+
114
+ ```tsx | pure
115
+
116
+ export type SnapshotResponse = {
117
+ data: Blob | string // Blob对象 或 Base64文本编码文本
118
+ width: number // 图片宽度
119
+ height: number // 图片高度
120
+ }
121
+
122
+ ```
123
+
124
+ ### lf.getSnapshotBase64(...)
125
+
126
+ 获取`Base64文本编码`文本。
127
+
128
+ ```ts
129
+
130
+ async getSnapshotBase64(backgroundColor?: string, fileType?: string) : Promise<SnapshotResponse>
131
+
132
+ // example
133
+ const { data : base64 } = await lf.getSnapshotBlob()
134
+ console.log(base64)
@@ -1,12 +1,58 @@
1
+ import LogicFlow from '@logicflow/core'
2
+ import { updateImageSource, copyCanvas } from './utils'
3
+
4
+ // 导出图片
5
+ export type ToImageOptions = {
6
+ /**
7
+ * 导出图片的格式,可选值为:`png`、`webp`、`gif`、`jpeg`、`svg`,默认值为 `png`
8
+ */
9
+ fileType?: string
10
+ /**
11
+ * 导出图片的宽度,通常无需设置,设置后可能会拉伸图形
12
+ */
13
+ width?: number
14
+ /**
15
+ * 导出图片的高度,通常无需设置,设置后可能会拉伸图形
16
+ */
17
+ height?: number
18
+ /**
19
+ * 导出图片的背景色,默认为透明
20
+ */
21
+ backgroundColor?: string
22
+ /**
23
+ * 导出图片的质量。
24
+ *
25
+ * 在指定图片格式为 `jpeg` 或 `webp` 的情况下,可以从 0 到 1 的区间内选择图片的质量,如果超出取值范围,将会使用默认值 0.92。导出为其他格式的图片时,该参数会被忽略。
26
+ */
27
+ quality?: number
28
+ /**
29
+ * 导出图片的内边距,即元素内容所在区域边界与图片边界的距离,单位为像素,默认为 40
30
+ */
31
+ padding?: number
32
+ /**
33
+ * 导出图片时是否开启局部渲染
34
+ * - `false`:将导出画布上所有的元素
35
+ * - `true`:只导出画面区域内的可见元素
36
+ */
37
+ partial?: boolean
38
+ }
39
+
40
+ // Blob | base64
41
+ export type SnapshotResponse = {
42
+ data: Blob | string
43
+ width: number
44
+ height: number
45
+ }
46
+
1
47
  /**
2
48
  * 快照插件,生成视图
3
49
  */
4
50
  export class Snapshot {
5
51
  static pluginName = 'snapshot'
6
- lf: any
52
+ lf: LogicFlow
7
53
  offsetX?: number
8
54
  offsetY?: number
9
- fileName: string = 'snapshot.png'
55
+ fileName?: string // 默认是 logic-flow.当前时间戳
10
56
  customCssRules: string
11
57
  useGlobalRules: boolean
12
58
 
@@ -14,38 +60,58 @@ export class Snapshot {
14
60
  this.lf = lf
15
61
  this.customCssRules = ''
16
62
  this.useGlobalRules = true
63
+
64
+ // TODO: 设置fileType为gif但是下载下来的还是png
65
+ // TODO: 完善静默模式不允许添加、操作元素能力
17
66
  /* 下载快照 */
18
- lf.getSnapshot = (fileName: string, backgroundColor: string) => {
19
- this.getSnapshot(fileName, backgroundColor)
20
- }
67
+ lf.getSnapshot = async (
68
+ fileName?: string,
69
+ toImageOptions?: ToImageOptions,
70
+ ) => await this.getSnapshot(fileName, toImageOptions)
71
+
21
72
  /* 获取Blob对象,用户图片上传 */
22
- lf.getSnapshotBlob = (backgroundColor: string) =>
23
- this.getSnapshotBlob(backgroundColor)
73
+ lf.getSnapshotBlob = async (backgroundColor?: string, fileType?: string) =>
74
+ await this.getSnapshotBlob(backgroundColor, fileType)
75
+
24
76
  /* 获取Base64对象,用户图片上传 */
25
- lf.getSnapshotBase64 = (backgroundColor: string) =>
26
- this.getSnapshotBase64(backgroundColor)
77
+ lf.getSnapshotBase64 = async (
78
+ backgroundColor?: string,
79
+ fileType?: string,
80
+ ) => await this.getSnapshotBase64(backgroundColor, fileType)
27
81
  }
28
82
 
29
- /* 获取svgRoot对象 */
30
- getSvgRootElement(lf) {
31
- const svgRootElement = lf.container.querySelector('.lf-canvas-overlay')
83
+ /**
84
+ * 获取svgRoot对象dom: 画布元素(不包含grid背景)
85
+ * @param lf
86
+ * @returns
87
+ */
88
+ private getSvgRootElement(lf: LogicFlow) {
89
+ const svgRootElement = lf.container.querySelector('.lf-canvas-overlay')!
32
90
  return svgRootElement
33
91
  }
34
92
 
35
- triggerDownload(imgURI: string) {
93
+ /**
94
+ * 通过 imgUrl 下载图片
95
+ * @param imgUrl
96
+ */
97
+ private triggerDownload(imgUrl: string) {
36
98
  const evt = new MouseEvent('click', {
37
99
  view: document.defaultView,
38
100
  bubbles: false,
39
101
  cancelable: true,
40
102
  })
41
103
  const a = document.createElement('a')
42
- a.setAttribute('download', this.fileName)
43
- a.setAttribute('href', imgURI)
104
+ a.setAttribute('download', this.fileName!)
105
+ a.setAttribute('href', imgUrl)
44
106
  a.setAttribute('target', '_blank')
45
107
  a.dispatchEvent(evt)
46
108
  }
47
109
 
48
- removeAnchor(element) {
110
+ /**
111
+ * 删除锚点
112
+ * @param element
113
+ */
114
+ private removeAnchor(element: ChildNode) {
49
115
  const { childNodes } = element
50
116
  let childLength = element.childNodes && element.childNodes.length
51
117
  for (let i = 0; i < childLength; i++) {
@@ -59,7 +125,11 @@ export class Snapshot {
59
125
  }
60
126
  }
61
127
 
62
- removeRotateControl(element) {
128
+ /**
129
+ * 删除旋转按钮
130
+ * @param element
131
+ */
132
+ private removeRotateControl(element: ChildNode) {
63
133
  const { childNodes } = element
64
134
  let childLength = element.childNodes && element.childNodes.length
65
135
  for (let i = 0; i < childLength; i++) {
@@ -73,27 +143,84 @@ export class Snapshot {
73
143
  }
74
144
  }
75
145
 
76
- /* 下载图片 */
77
- getSnapshot(fileName: string, backgroundColor: string) {
78
- this.fileName = fileName || `logic-flow.${Date.now()}.png`
146
+ /**
147
+ * 下载前的处理画布工作:局部渲染模式处理、静默模式处理
148
+ * @param fileName
149
+ * @param toImageOptions
150
+ */
151
+ async getSnapshot(fileName?: string, toImageOptions?: ToImageOptions) {
152
+ const curPartial = this.lf.graphModel.getPartial()
153
+ const { partial = curPartial } = toImageOptions ?? {}
154
+ // 获取流程图配置
155
+ const editConfig = this.lf.getEditConfig()
156
+ // 开启静默模式:如果元素多的话 避免用户交互 感知卡顿
157
+ this.lf.updateEditConfig({
158
+ isSilentMode: true,
159
+ stopScrollGraph: true,
160
+ stopMoveGraph: true,
161
+ })
162
+ // 画布当前渲染模式和用户导出渲染模式不一致时,需要更新画布
163
+ if (curPartial !== partial) {
164
+ this.lf.graphModel.setPartial(partial)
165
+ this.lf.graphModel.eventCenter.once('graph:updated', async () => {
166
+ await this.snapshot(fileName, toImageOptions)
167
+ // 恢复原来渲染模式
168
+ this.lf.graphModel.setPartial(curPartial)
169
+ })
170
+ } else {
171
+ await this.snapshot(fileName, toImageOptions)
172
+ }
173
+ // 恢复原来配置
174
+ this.lf.updateEditConfig(editConfig)
175
+ }
176
+
177
+ /**
178
+ * 下载图片
179
+ * @param fileName
180
+ * @param toImageOptions
181
+ */
182
+ private async snapshot(fileName?: string, toImageOptions?: ToImageOptions) {
183
+ const { fileType = 'png', quality } = toImageOptions ?? {}
184
+ this.fileName = `${fileName ?? `logic-flow.${Date.now()}`}.${fileType}`
79
185
  const svg = this.getSvgRootElement(this.lf)
80
- this.getCanvasData(svg, backgroundColor).then(
81
- (canvas: HTMLCanvasElement) => {
82
- const imgURI = canvas
83
- .toDataURL('image/png')
84
- .replace('image/png', 'image/octet-stream')
85
- this.triggerDownload(imgURI)
86
- },
87
- )
186
+ await updateImageSource(svg as SVGElement)
187
+ if (fileType === 'svg') {
188
+ const copy = this.cloneSvg(svg)
189
+ const svgString = new XMLSerializer().serializeToString(copy)
190
+ const blob = new Blob([svgString], {
191
+ type: 'image/svg+xml;charset=utf-8',
192
+ })
193
+ const url = URL.createObjectURL(blob)
194
+ this.triggerDownload(url)
195
+ } else {
196
+ this.getCanvasData(svg, toImageOptions ?? {}).then(
197
+ (canvas: HTMLCanvasElement) => {
198
+ // canvas元素 => url image/octet-stream: 确保所有浏览器都能正常下载
199
+ const imgUrl = canvas
200
+ .toDataURL(`image/${fileType}`, quality)
201
+ .replace(`image/${fileType}`, 'image/octet-stream')
202
+ this.triggerDownload(imgUrl)
203
+ },
204
+ )
205
+ }
88
206
  }
89
207
 
90
- /* 获取base64对象 */
91
- getSnapshotBase64(backgroundColor: string) {
208
+ /**
209
+ * 获取base64对象
210
+ * @param backgroundColor
211
+ * @param fileType
212
+ * @returns
213
+ */
214
+ private async getSnapshotBase64(
215
+ backgroundColor?: string,
216
+ fileType?: string,
217
+ ): Promise<SnapshotResponse> {
92
218
  const svg = this.getSvgRootElement(this.lf)
219
+ await updateImageSource(svg as SVGElement)
93
220
  return new Promise((resolve) => {
94
- this.getCanvasData(svg, backgroundColor).then(
221
+ this.getCanvasData(svg, { backgroundColor }).then(
95
222
  (canvas: HTMLCanvasElement) => {
96
- const base64 = canvas.toDataURL('image/png')
223
+ const base64 = canvas.toDataURL(`image/${fileType ?? 'png'}`)
97
224
  // 输出图片数据以及图片宽高
98
225
  resolve({
99
226
  data: base64,
@@ -105,33 +232,56 @@ export class Snapshot {
105
232
  })
106
233
  }
107
234
 
108
- /* 获取Blob对象 */
109
- getSnapshotBlob(backgroundColor: string) {
235
+ /**
236
+ * 获取Blob对象
237
+ * @param backgroundColor
238
+ * @param fileType
239
+ * @returns
240
+ */
241
+ private async getSnapshotBlob(
242
+ backgroundColor?: string,
243
+ fileType?: string,
244
+ ): Promise<SnapshotResponse> {
110
245
  const svg = this.getSvgRootElement(this.lf)
246
+ await updateImageSource(svg as SVGElement)
111
247
  return new Promise((resolve) => {
112
- this.getCanvasData(svg, backgroundColor).then(
248
+ this.getCanvasData(svg, { backgroundColor }).then(
113
249
  (canvas: HTMLCanvasElement) => {
114
- canvas.toBlob((blob) => {
115
- // 输出图片数据以及图片宽高
116
- resolve({
117
- data: blob,
118
- width: canvas.width,
119
- height: canvas.height,
120
- })
121
- }, 'image/png')
250
+ canvas.toBlob(
251
+ (blob) => {
252
+ // 输出图片数据以及图片宽高
253
+ resolve({
254
+ data: blob!,
255
+ width: canvas.width,
256
+ height: canvas.height,
257
+ })
258
+ },
259
+ `image/${fileType ?? 'png'}`,
260
+ )
122
261
  },
123
262
  )
124
263
  })
125
264
  }
126
265
 
127
- getClassRules() {
266
+ /**
267
+ * 获取脚本css样式
268
+ * @returns
269
+ */
270
+ private getClassRules(): string {
128
271
  let rules = ''
129
272
  if (this.useGlobalRules) {
130
273
  const { styleSheets } = document
131
274
  for (let i = 0; i < styleSheets.length; i++) {
132
275
  const sheet = styleSheets[i]
133
- for (let j = 0; j < sheet.cssRules.length; j++) {
134
- rules += sheet.cssRules[j].cssText
276
+ // 这里是为了过滤掉不同源css脚本
277
+ try {
278
+ for (let j = 0; j < sheet.cssRules.length; j++) {
279
+ rules += sheet.cssRules[j].cssText
280
+ }
281
+ } catch (error) {
282
+ console.log(
283
+ 'CSS scripts from different sources have been filtered out',
284
+ )
135
285
  }
136
286
  }
137
287
  }
@@ -141,37 +291,19 @@ export class Snapshot {
141
291
  return rules
142
292
  }
143
293
 
144
- // 获取图片生成中中间产物canvas对象,用户转换为其他需要的格式
145
- getCanvasData(
146
- svg: SVGGraphicsElement,
147
- backgroundColor: string,
148
- ): Promise<any> {
149
- // TODO: 确认返回 Promise 的类型
150
- const copy = svg.cloneNode(true)
151
- const graph = copy.lastChild
152
- let childLength = graph?.childNodes?.length
153
- if (childLength) {
154
- for (let i = 0; i < childLength; i++) {
155
- const lfLayer = graph?.childNodes[i] as SVGGraphicsElement
156
- // 只保留包含节点和边的基础图层进行下载,其他图层删除
157
- const layerClassList =
158
- lfLayer.classList && Array.from(lfLayer.classList)
159
- if (layerClassList && layerClassList.indexOf('lf-base') < 0) {
160
- graph?.removeChild(graph.childNodes[i])
161
- childLength--
162
- i--
163
- } else {
164
- // 删除锚点
165
- const lfBase = graph?.childNodes[i]
166
- lfBase &&
167
- lfBase.childNodes.forEach((item) => {
168
- const element = item as SVGGraphicsElement
169
- this.removeAnchor(element.firstChild)
170
- this.removeRotateControl(element.firstChild)
171
- })
172
- }
173
- }
174
- }
294
+ /**
295
+ * 获取图片生成中间产物canvas对象,用户转换为其他需要的格式
296
+ * @param svg
297
+ * @param toImageOptions
298
+ * @returns
299
+ */
300
+ private async getCanvasData(
301
+ svg: Element,
302
+ toImageOptions: ToImageOptions,
303
+ ): Promise<HTMLCanvasElement> {
304
+ const { width, height, backgroundColor, padding = 40 } = toImageOptions
305
+ const copy = this.cloneSvg(svg, false)
306
+
175
307
  let dpr = window.devicePixelRatio || 1
176
308
  if (dpr < 1) {
177
309
  // https://github.com/didi/LogicFlow/issues/1222
@@ -187,46 +319,50 @@ export class Snapshot {
187
319
  // 当dpr小于1的时候,我们强制转化为1,并不会产生绘制模糊等问题
188
320
  dpr = 1
189
321
  }
190
- const canvas = document.createElement('canvas')
191
322
  /*
192
323
  为了计算真实宽高需要取图的真实dom
193
324
  真实dom存在缩放影响其宽高数值
194
325
  在得到真实宽高后除以缩放比例即可得到正常宽高
195
326
  */
327
+
196
328
  const base = this.lf.graphModel.rootEl.querySelector('.lf-base')
197
329
  const bbox = (base as Element).getBoundingClientRect()
198
- const layout = this.lf.container
199
- .querySelector('.lf-canvas-overlay')
200
- .getBoundingClientRect()
330
+ const layoutCanvas = this.lf.container.querySelector('.lf-canvas-overlay')!
331
+ const layout = layoutCanvas.getBoundingClientRect()
201
332
  const offsetX = bbox.x - layout.x
202
333
  const offsetY = bbox.y - layout.y
203
334
  const { graphModel } = this.lf
204
335
  const { transformModel } = graphModel
205
336
  const { SCALE_X, SCALE_Y, TRANSLATE_X, TRANSLATE_Y } = transformModel
206
- // offset值加10,保证图形不会紧贴着下载图片的左边和上边
207
- ;(copy.lastChild as SVGGElement).style.transform = `matrix(1, 0, 0, 1, ${
208
- (-offsetX + TRANSLATE_X) * (1 / SCALE_X) + 10
209
- }, ${(-offsetY + TRANSLATE_Y) * (1 / SCALE_Y) + 10})`
337
+ ;(copy.lastChild as SVGElement).style.transform = `matrix(1, 0, 0, 1, ${
338
+ (-offsetX + TRANSLATE_X) * (1 / SCALE_X)
339
+ }, ${(-offsetY + TRANSLATE_Y) * (1 / SCALE_Y)})`
340
+ // 包含所有元素的最小宽高
210
341
  const bboxWidth = Math.ceil(bbox.width / SCALE_X)
211
342
  const bboxHeight = Math.ceil(bbox.height / SCALE_Y)
212
- // width,height 值加40,保证图形不会紧贴着下载图片的右边和下边
343
+ const canvas = document.createElement('canvas')
213
344
  canvas.style.width = `${bboxWidth}px`
214
345
  canvas.style.height = `${bboxHeight}px`
215
- canvas.width = bboxWidth * dpr + 80
216
- canvas.height = bboxHeight * dpr + 80
346
+ // 宽高值 默认加padding 40,保证图形不会紧贴着下载图片
347
+ canvas.width = bboxWidth * dpr + padding * 2
348
+ canvas.height = bboxHeight * dpr + padding * 2
217
349
  const ctx = canvas.getContext('2d')
218
350
  if (ctx) {
351
+ // 清空canvas
219
352
  ctx.clearRect(0, 0, canvas.width, canvas.height)
220
353
  ctx.scale(dpr, dpr)
221
354
  // 如果有背景色,设置流程图导出的背景色
222
355
  if (backgroundColor) {
223
356
  ctx.fillStyle = backgroundColor
224
- ctx.fillRect(0, 0, bboxWidth * dpr + 80, bboxHeight * dpr + 80)
357
+ ctx.fillRect(0, 0, canvas.width, canvas.height)
225
358
  } else {
226
- ctx.clearRect(0, 0, bboxWidth, bboxHeight)
359
+ ctx.clearRect(0, 0, canvas.width, canvas.height)
227
360
  }
228
361
  }
362
+
229
363
  const img = new Image()
364
+
365
+ // 设置css样式
230
366
  const style = document.createElement('style')
231
367
  style.innerHTML = this.getClassRules()
232
368
  const foreignObject = document.createElement('foreignObject')
@@ -238,26 +374,37 @@ export class Snapshot {
238
374
  try {
239
375
  if (isFirefox) {
240
376
  createImageBitmap(img, {
241
- resizeWidth: canvas.width,
242
- resizeHeight: canvas.height,
377
+ resizeWidth:
378
+ width && height
379
+ ? copyCanvas(canvas, width, height).width
380
+ : canvas.width,
381
+ resizeHeight:
382
+ width && height
383
+ ? copyCanvas(canvas, width, height).height
384
+ : canvas.height,
243
385
  }).then((imageBitmap) => {
244
- // 在回调函数中使用 drawImage() 方法绘制图像
245
- ctx?.drawImage(imageBitmap, 0, 0)
246
- resolve(canvas)
386
+ ctx?.drawImage(imageBitmap, padding / dpr, padding / dpr)
387
+ resolve(
388
+ width && height ? copyCanvas(canvas, width, height) : canvas,
389
+ )
247
390
  })
248
391
  } else {
249
- ctx?.drawImage(img, 0, 0)
250
- resolve(canvas)
392
+ ctx?.drawImage(img, padding / dpr, padding / dpr)
393
+ resolve(
394
+ width && height ? copyCanvas(canvas, width, height) : canvas,
395
+ )
251
396
  }
397
+ // 如果局部渲染本来是开启的,继续开启
398
+ // partial && this.lf.graphModel.setPartial(true)
252
399
  } catch (e) {
253
- ctx?.drawImage(img, 0, 0)
254
- resolve(canvas)
400
+ ctx?.drawImage(img, padding / dpr, padding / dpr)
401
+ resolve(width && height ? copyCanvas(canvas, width, height) : canvas)
255
402
  }
256
403
  }
404
+
257
405
  /*
258
406
  因为svg中存在dom存放在foreignObject元素中
259
- SVG图形转成img对象
260
- todo: 会导致一些清晰度问题这个需要再解决
407
+ svg dom => Base64编码字符串 挂载到img
261
408
  fixme: XMLSerializer的中的css background url不会下载图片
262
409
  */
263
410
  const svg2Img = `data:image/svg+xml;charset=utf-8,${new XMLSerializer().serializeToString(
@@ -270,6 +417,48 @@ export class Snapshot {
270
417
  img.src = imgSrc
271
418
  })
272
419
  }
420
+
421
+ /**
422
+ * 克隆并处理画布节点
423
+ * @param svg
424
+ * @returns
425
+ */
426
+ private cloneSvg(svg: Element, addStyle: boolean = true): Node {
427
+ const copy = svg.cloneNode(true)
428
+ const graph = copy.lastChild
429
+ let childLength = graph?.childNodes?.length
430
+ if (childLength) {
431
+ for (let i = 0; i < childLength; i++) {
432
+ const lfLayer = graph?.childNodes[i] as SVGGraphicsElement
433
+ // 只保留包含节点和边的基础图层进行下载,其他图层删除
434
+ const layerClassList =
435
+ lfLayer.classList && Array.from(lfLayer.classList)
436
+ if (layerClassList && layerClassList.indexOf('lf-base') < 0) {
437
+ graph?.removeChild(graph.childNodes[i])
438
+ childLength--
439
+ i--
440
+ } else {
441
+ // 删除锚点
442
+ const lfBase = graph?.childNodes[i]
443
+ lfBase &&
444
+ lfBase.childNodes.forEach((item) => {
445
+ const element = item as SVGGraphicsElement
446
+ this.removeAnchor(element.firstChild!)
447
+ this.removeRotateControl(element.firstChild!)
448
+ })
449
+ }
450
+ }
451
+ }
452
+ // 设置css样式
453
+ if (addStyle) {
454
+ const style = document.createElement('style')
455
+ style.innerHTML = this.getClassRules()
456
+ const foreignObject = document.createElement('foreignObject')
457
+ foreignObject.appendChild(style)
458
+ copy.appendChild(foreignObject)
459
+ }
460
+ return copy
461
+ }
273
462
  }
274
463
 
275
464
  export default Snapshot