diff --git a/packages/g6/__tests__/unit/behaviors/drag-canvas.spec.ts b/packages/g6/__tests__/unit/behaviors/drag-canvas.spec.ts
index 66db8c07b40..f91e5c02cc5 100644
--- a/packages/g6/__tests__/unit/behaviors/drag-canvas.spec.ts
+++ b/packages/g6/__tests__/unit/behaviors/drag-canvas.spec.ts
@@ -80,6 +80,31 @@ describe('behavior drag canvas', () => {
await expect(graph).toMatchSnapshot(__filename);
});
+ it('drag in the x-axis direction', () => {
+ graph.updateBehavior({ key: 'drag-canvas', direction: 'x' });
+
+ const [x, y] = graph.getPosition();
+ graph.emit(CommonEvent.KEY_DOWN, { key: 'ArrowRight' });
+ graph.emit(CommonEvent.KEY_UP, { key: 'ArrowRight' });
+ graph.emit(CommonEvent.KEY_DOWN, { key: 'ArrowDown' });
+ graph.emit(CommonEvent.KEY_UP, { key: 'ArrowDown' });
+
+ expect(graph.getPosition()).toBeCloseTo([x + 20, y]);
+ });
+
+ it('drag in the y-axis direction', () => {
+ graph.updateBehavior({ key: 'drag-canvas', direction: 'y' });
+
+ const [x, y] = graph.getPosition();
+ graph.emit(CommonEvent.KEY_DOWN, { key: 'ArrowRight' });
+ graph.emit(CommonEvent.KEY_UP, { key: 'ArrowRight' });
+ graph.emit(CommonEvent.KEY_DOWN, { key: 'ArrowDown' });
+ graph.emit(CommonEvent.KEY_UP, { key: 'ArrowDown' });
+
+ expect(graph.getPosition()).toBeCloseTo([x, y + 20]);
+ graph.updateBehavior({ key: 'drag-canvas', direction: 'both' });
+ });
+
it('onFinish with key', async () => {
const onFinish = jest.fn();
graph.updateBehavior({ key: 'drag-canvas', onFinish });
diff --git a/packages/g6/src/behaviors/drag-canvas.ts b/packages/g6/src/behaviors/drag-canvas.ts
index 270baf4c00f..4b13e88444d 100644
--- a/packages/g6/src/behaviors/drag-canvas.ts
+++ b/packages/g6/src/behaviors/drag-canvas.ts
@@ -28,6 +28,19 @@ export interface DragCanvasOptions extends BaseBehaviorOptions {
* @defaultValue true
*/
enable?: boolean | ((event: IPointerEvent | IKeyboardEvent) => boolean);
+ /**
+ * 允许拖拽方向
+ * - `'x'`: 只允许水平拖拽
+ * - `'y'`: 只允许垂直拖拽
+ * - `'both'`: 不受限制,允许水平和垂直拖拽
+ *
+ * Allowed drag direction
+ * - `'x'`: Only allow horizontal drag
+ * - `'y'`: Only allow vertical drag
+ * - `'both'`: Allow horizontal and vertical drag
+ * @defaultValue `'both'`
+ */
+ direction?: 'x' | 'y' | 'both';
/**
* 触发拖拽的方式,默认使用指针按下拖拽
*
@@ -66,6 +79,7 @@ export class DragCanvas extends BaseBehavior {
return true;
},
sensitivity: 10,
+ direction: 'both',
};
private shortcut: Shortcut;
@@ -155,7 +169,16 @@ export class DragCanvas extends BaseBehavior {
* @internal
*/
protected async translate(offset: Vector2, animation?: ViewportAnimationEffectTiming) {
- await this.context.graph.translateBy(offset, animation);
+ let [dx, dy] = offset;
+
+ const { direction } = this.options;
+ if (direction === 'x') {
+ dy = 0;
+ } else if (direction === 'y') {
+ dx = 0;
+ }
+
+ await this.context.graph.translateBy([dx, dy], animation);
}
private validate(event: IPointerEvent | IKeyboardEvent) {