缩放画布 ZoomCanvas
概述
ZoomCanvas 是 G6 中用于实现画布缩放功能的内置交互,支持通过鼠标滚轮或键盘快捷键调整画布缩放比例。这是图可视化中最常用的交互之一,能帮助用户查看图的整体结构和局部细节。
使用场景
这一交互主要用于:
- 浏览大规模图数据,在整体与细节之间自由切换
- 聚焦到特定区域进行详细分析
在线体验
import { createGraph } from '/demo-runtime.ts';
createGraph(
{
data: { nodes: [{ id: 'node-1' }] },
layout: { type: 'force' },
behaviors: [
{
type: 'zoom-canvas',
key: 'zoom-canvas',
},
],
node: { style: { fill: '#873bf4' } },
edge: { style: { stroke: '#8b9baf' } },
plugins: [{ type: 'grid-line', size: 30 }],
},
{ width: 600, height: 300 },
(gui, graph) => {
const options = {
key: 'zoom-canvas',
type: 'zoom-canvas',
animation: true,
enable: true,
sensitivity: 1,
trigger: 'Use wheel by default',
};
const optionFolder = gui.addFolder('ZoomCanvas Options');
optionFolder.add(options, 'type').disable(true);
optionFolder.add(options, 'animation');
optionFolder.add(options, 'enable');
optionFolder.add(options, 'sensitivity', 0, 10, 1);
optionFolder.add(options, 'trigger', {
'Use wheel by default': [],
'Control+Wheel': ['Control'],
'zoomIn:Ctrl+1 zoomOut:Ctrl+2 reset:Ctrl+0': {
zoomIn: ['Control', '1'],
zoomOut: ['Control', '2'],
reset: ['Control', '0'],
},
});
optionFolder.onChange(({ property, value }) => {
graph.updateBehavior({
key: 'zoom-canvas',
[property]: value,
});
graph.render();
});
},
);
import { Graph } from '@antv/g6';
import GUI from 'lil-gui';
export function addPanel(renderPanel: (gui: GUI) => void) {
const gui = new GUI({ container: document.body });
gui.title('Control');
Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' });
renderPanel(gui);
addEventListener('pagehide', () => gui.destroy(), { once: true });
}
export async function createGraph(
options: ConstructorParameters<typeof Graph>[0],
size: { width?: number; height?: number } = {},
renderPanel?: (gui: GUI, graph: Graph) => void,
) {
const container = document.createElement('div');
Object.assign(container.style, {
width: '100%',
maxWidth: `${size.width || 600}px`,
height: `${size.height || 400}px`,
});
document.getElementById('container')!.append(container);
const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true });
addEventListener('pagehide', () => graph.destroy(), { once: true });
await graph.render();
if (renderPanel) addPanel((gui) => renderPanel(gui, graph));
return container;
}基本用法
在图配置中添加这一交互:
1. 快速配置(静态)
使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改:
const graph = new Graph({
// 其他配置...
behaviors: ['zoom-canvas'],
});
2. 对象配置(推荐)
使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置:
const graph = new Graph({
// 其他配置...
behaviors: [
{
type: 'zoom-canvas',
key: 'zoom-canvas-1', // 为交互指定标识符,方便动态更新
sensitivity: 1.5, // 设置灵敏度
},
],
});
配置项
| 配置项 | 说明 | 类型 | 默认值 | 必选 |
|---|---|---|---|---|
| type | 交互类型名称 | string | zoom-canvas |
✓ |
| animation | 缩放动画效果设置 | ViewportAnimationEffectTiming | { duration: 200 } |
|
| enable | 是否启用该交互 | boolean | ((event: Event) => boolean) | true | |
| origin | 缩放中心点(视口坐标) | Point | - | |
| onFinish | 缩放完成时的回调函数 | () => void | - | |
| preventDefault | 是否阻止浏览器默认事件 | boolean | true | |
| sensitivity | 缩放灵敏度,值越大缩放速度越快 | number | 1 | |
| trigger | 触发缩放的方式,支持滚轮和键盘快捷键,配置项 | string[] | object | - |
Trigger
trigger有两种使用方式,分别适用于不同场景:
方式一:与滚轮结合的修饰键
当你希望只有在按下某些键的同时滚动滚轮才触发缩放时,可以这样配置:
{
trigger: ['Control']; // 按住 Control 键同时滚动鼠标滚轮才能缩放
}
常见的修饰键有:
ControlShiftAlt
不知道键盘按键对应什么值?请参考 MDN Key Values。
方式二:纯键盘快捷键
当你希望完全使用键盘控制缩放操作时,可以设置组合键:
{
trigger: {
zoomIn: ['Control', '+'], // 放大快捷键
zoomOut: ['Control', '-'], // 缩小快捷键
reset: ['Control', '0'] // 重置缩放比例快捷键
}
}
代码示例
基础缩放功能
const graph = new Graph({
container: 'container',
width: 800,
height: 600,
behaviors: ['zoom-canvas'],
});
自定义缩放中心
const graph = new Graph({
// 其他配置...
behaviors: [
function () {
return {
type: 'zoom-canvas',
origin: this.getCanvasCenter(), // 以视口中心为原点进行缩放
};
},
],
});
自定义缩放灵敏度
const graph = new Graph({
// 其他配置...
behaviors: [
{
type: 'zoom-canvas',
sensitivity: 0.8, // 降低灵敏度,缩放变化更平缓
},
],
});
使用Shift+滚轮进行缩放
const graph = new Graph({
// 其他配置...
behaviors: [
{
type: 'zoom-canvas',
trigger: ['Shift'], // 按住 Shift 键同时滚动才能缩放
},
],
});
使用键盘快捷键控制缩放
const graph = new Graph({
// 其他配置...
behaviors: [
{
type: 'zoom-canvas',
trigger: {
zoomIn: ['Control', '='], // Ctrl + = 放大
zoomOut: ['Control', '-'], // Ctrl + - 缩小
reset: ['Control', '0'], // Ctrl + 0 重置
},
},
],
});
支持移动端双指缩放
const graph = new Graph({
// 其他配置...
behaviors: [
{
type: 'zoom-canvas',
// PC 端其他配置...
},
function () {
return {
type: 'zoom-canvas',
trigger: ['pinch'],
sensitivity: 0.8, // 降低灵敏度,缩放变化更平缓
origin: this.getCanvasCenter(), // 以视口中心为原点进行缩放
};
},
],
});
常见问题
1. 画布缩放超出了预期范围怎么办?
为避免缩放过大或过小,可以设置缩放限制:
const graph = new Graph({
// 其他配置...
zoomRange: [0.5, 3], // 允许缩小到50%和放大到300%
behaviors: ['zoom-canvas'],
});
2. 如何与其他交互结合使用?
缩放与拖拽是常见的组合,实现完整的导航体验:
const graph = new Graph({
// 其他配置...
behaviors: ['drag-canvas', 'zoom-canvas'],
});
3. 触控板双指操作下,与 scroll-canvas 同时使用时的冲突
在触控板上,双指滑动(用于滚动)和双指捏合(用于缩放)手势通常都会被解析为 wheel 事件。
由于 zoom-canvas 和 scroll-canvas 默认都会响应 wheel 事件,当它们同时使用时会产生冲突,例如一个手势会同时触发滚动和缩放。
你可以通过检查 event.ctrlKey 属性来解决这个问题。在多数平台上,捏合手势会使 event.ctrlKey 为 true,而滑动则不会。这允许你有条件地仅为捏合手势启用 zoom-canvas。
import { Graph } from '@antv/g6';
const graph = new Graph({
container: 'container',
layout: {
type: 'grid',
},
data: {
nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }],
},
behaviors: [
'scroll-canvas',
{
key: 'custom-zoom-canvas',
type: 'zoom-canvas',
enable: (event) => {
return event.ctrlKey; // ctrlKey 为 true 时,是双指捏合或扩张操作,false 时是双指滑动操作
},
},
],
});
graph.render();
import { Graph } from '@antv/g6';
import GUI from 'lil-gui';
export function addPanel(renderPanel: (gui: GUI) => void) {
const gui = new GUI({ container: document.body });
gui.title('Control');
Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' });
renderPanel(gui);
addEventListener('pagehide', () => gui.destroy(), { once: true });
}
export async function createGraph(
options: ConstructorParameters<typeof Graph>[0],
size: { width?: number; height?: number } = {},
renderPanel?: (gui: GUI, graph: Graph) => void,
) {
const container = document.createElement('div');
Object.assign(container.style, {
width: '100%',
maxWidth: `${size.width || 600}px`,
height: `${size.height || 400}px`,
});
document.getElementById('container')!.append(container);
const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true });
addEventListener('pagehide', () => graph.destroy(), { once: true });
await graph.render();
if (renderPanel) addPanel((gui) => renderPanel(gui, graph));
return container;
}实际案例
import { Graph } from '@antv/g6';
const graph = new Graph({
container: 'container',
layout: {
type: 'grid',
},
data: {
nodes: [{ id: 'node1' }, { id: 'node2' }, { id: 'node3' }, { id: 'node4' }, { id: 'node5' }],
edges: [
{ source: 'node1', target: 'node2' },
{ source: 'node1', target: 'node3' },
{ source: 'node1', target: 'node4' },
{ source: 'node2', target: 'node3' },
{ source: 'node3', target: 'node4' },
{ source: 'node4', target: 'node5' },
],
},
behaviors: ['zoom-canvas'],
});
graph.render();
import { Graph } from '@antv/g6';
import GUI from 'lil-gui';
export function addPanel(renderPanel: (gui: GUI) => void) {
const gui = new GUI({ container: document.body });
gui.title('Control');
Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' });
renderPanel(gui);
addEventListener('pagehide', () => gui.destroy(), { once: true });
}
export async function createGraph(
options: ConstructorParameters<typeof Graph>[0],
size: { width?: number; height?: number } = {},
renderPanel?: (gui: GUI, graph: Graph) => void,
) {
const container = document.createElement('div');
Object.assign(container.style, {
width: '100%',
maxWidth: `${size.width || 600}px`,
height: `${size.height || 400}px`,
});
document.getElementById('container')!.append(container);
const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true });
addEventListener('pagehide', () => graph.destroy(), { once: true });
await graph.render();
if (renderPanel) addPanel((gui) => renderPanel(gui, graph));
return container;
}