d3中拖动卡顿现象

在画力导向图的时候,能够拖动是很常见的需求。

在d3中,监听缩放事件就可以很容易的实现拖动效果。

const svg = d3.select(this.$refs.svg);
svg
  .attr('width', 300)
  .attr('height', 300)
  .attr('viewBox', '-150 -150 300 300');
const g = svg.append('g');
g.append('circle')
  .attr('r', 10)
  .attr('fill', '#a23');

g.call(
  d3.zoom().on('zoom', () => {
    g.attr('transform', d3.event.transform);
  })
);

效果如下

See the Pen
gOYoRVv
by Leevare (@leevare)
on CodePen.

当按住小红点开始拖动时,会发现拖动起来十分卡顿。

由于上述代码将zoom绑定在g这个分组上,但是在zoom或拖动的时候还会去操作gtransform属性,同时进行两种操作会导致卡顿的问题,所以,将zoom绑定在外层的svg上即可。

svg.call(
  d3.zoom().on('zoom', () => {
    g.attr('transform', d3.event.transform);
  })
);

查看效果:

See the Pen
XWrzLeL
by Leevare (@leevare)
on CodePen.

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注