在画力导向图的时候,能够拖动是很常见的需求。
在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
或拖动的时候还会去操作g
的transform
属性,同时进行两种操作会导致卡顿的问题,所以,将zoom
绑定在外层的svg
上即可。
svg.call(
d3.zoom().on('zoom', () => {
g.attr('transform', d3.event.transform);
})
);
查看效果:
See the Pen
XWrzLeL by Leevare (@leevare)
on CodePen.
如果觉得我的文章对您有用,请您随意打赏。您的支持将鼓励我更加努力创作!
如无特殊声明,文章均为原创,若有不正之处,万望告知。转载请附上原文地址,十分感谢!