Canvas画背景网格线

我们有一个vis.js做的关系图,要让用户在页面上拖动节点,自己排版布局。由于页面是空白的,用户排版的时候缺乏参考,可能拍得会比较乱,因此我考虑画一些背景网格线,帮助用户定位。

作图

作图原理很简单,就是在Canvas画布上画上横纵虚线即可。

下面这个示例为了追求开发速度,写了不少硬编码;正式项目中应该去掉这些硬编码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 在背景上画一些格子,辅助排版
*/
function drawGrid(context) {
context = context || $('canvas')[0].getContext("2d")
context.lineWidth = 1;
context.strokeStyle = "#CECBCE";
context.setLineDash([5]);
let offset = 800;
let padding = 50;
for (let i = 0; i < 30; i++) {
context.beginPath();
context.moveTo(offset * -1, i * padding - offset)
context.lineTo(2000, i * padding - offset)
context.stroke();

context.beginPath();
context.moveTo(i * padding - offset, offset * -1)
context.lineTo(i * padding - offset, 2000)
context.stroke();
}
context.setLineDash([]);
}

性能优化

功能实现后,我发现一旦用户拖动节点,就会不断触发网格线的重新绘制,导致页面非常卡。为了解决这个问题,我做了一些处理,在用户拖动节点的过程中,不进行页面的绘制:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 为了减少画网格线的频率,这里去掉了拖动期间的画图
network.on('beforeDrawing', function (context) {
if (drawing) {
return;
}
drawGrid(context)
})
network.on('dragStart', function () {
drawing = true;
})
network.on('dragEnd', function () {
drawing = false;

exportHandler.upload()
})

修改后,就一点都不卡了,操作很流畅。