diff --git a/packages/g6/__tests__/bugs/graph-draw-after-clear.spec.ts b/packages/g6/__tests__/bugs/graph-draw-after-clear.spec.ts
new file mode 100644
index 00000000000..a4de275115f
--- /dev/null
+++ b/packages/g6/__tests__/bugs/graph-draw-after-clear.spec.ts
@@ -0,0 +1,17 @@
+import { elementEdgeLine } from '@@/demos';
+import { createDemoGraph, sleep } from '@@/utils';
+
+it('graph draw after clear', async () => {
+ const graph = await createDemoGraph(elementEdgeLine);
+
+ const data = graph.getData();
+
+ await graph.clear();
+
+ await sleep(200);
+
+ graph.addData(data);
+ await graph.draw();
+
+ await expect(graph).toMatchSnapshot(__filename);
+});
diff --git a/packages/g6/__tests__/snapshots/bugs/graph-draw-after-clear/default.svg b/packages/g6/__tests__/snapshots/bugs/graph-draw-after-clear/default.svg
new file mode 100644
index 00000000000..b30da88a6de
--- /dev/null
+++ b/packages/g6/__tests__/snapshots/bugs/graph-draw-after-clear/default.svg
@@ -0,0 +1,254 @@
+
diff --git a/packages/g6/src/runtime/data.ts b/packages/g6/src/runtime/data.ts
index 3f433e50521..ffb399206a7 100644
--- a/packages/g6/src/runtime/data.ts
+++ b/packages/g6/src/runtime/data.ts
@@ -85,12 +85,6 @@ export class DataController {
}
}
- /**
- * [警告] 此 API 仅供 Element Controller 调用
- *
- * [WARNING] This API is only for Element Controller
- * @returns 数据变更 | data changes
- */
public getChanges(): DataChange[] {
return this.changes;
}
diff --git a/packages/g6/src/runtime/element.ts b/packages/g6/src/runtime/element.ts
index 08c85193ddb..9ac233a19ec 100644
--- a/packages/g6/src/runtime/element.ts
+++ b/packages/g6/src/runtime/element.ts
@@ -848,13 +848,23 @@ export class ElementController {
)?.finished;
}
- public destroy() {
- this.container.destroy();
+ /**
+ * 清空所有元素
+ *
+ * clear all elements
+ */
+ public clear() {
+ this.container.children.forEach((element) => element.destroy());
this.elementMap = {};
this.shapeTypeMap = {};
this.defaultStyle = {};
this.stateStyle = {};
this.paletteStyle = {};
+ }
+
+ public destroy() {
+ this.clear();
+ this.container.destroy();
// @ts-expect-error force delete
this.context = {};
}
diff --git a/packages/g6/src/runtime/graph.ts b/packages/g6/src/runtime/graph.ts
index cdde2522b9c..63082754045 100644
--- a/packages/g6/src/runtime/graph.ts
+++ b/packages/g6/src/runtime/graph.ts
@@ -1200,8 +1200,10 @@ export class Graph extends EventEmitter {
* @apiCategory canvas
*/
public async clear(): Promise {
- this.context.model.setData({});
- await this.draw();
+ const { model, element } = this.context;
+ model.setData({});
+ model.clearChanges();
+ element?.clear();
}
/**