问题描述
Tldr;拖动SVG会导致它旋转和翻译。
我正在尝试实现拖动和缩放使用D3(v.4)作为Angular服务的一部分的SVG组上的事件。
I am trying to implement dragging and zooming events on an SVG group using D3 (v.4) as part of an Angular service.
this.unitGroup = this.svg.append('g')
.attr('id', 'unitGroup')
.call(this.drag)
.call(this.zoom);
拖动翻译SVG。
drag = d3.drag()
.on('start', () => {
console.log('drag start');
this.setClickOrigin(d3.event);
})
.on('drag', (d, i, n) => {
const target = d3.select(n[i]).node() as any;
const m = target.getCTM();
const x = d3.event.x - this.clickOrigin.x;
const y = d3.event.y - this.clickOrigin.y;
this.setClickOrigin(d3.event);
this.translate(target, x, y);
});
缩放时旋转SVG。
zoom = d3.zoom()
.on('zoom', (d, i, n) => {
const target = d3.select(n[i]).node() as any;
const m = target.getCTM();
const b = target.getBBox();
const dir = (d3.event.sourceEvent.deltaY > 0) ? 1 : -1;
this.rotate(target, dir);
});
我的原始代码工作正常。但是,将它集成到Angular中会引发一些问题。
My original code worked fine. However, integrating it into Angular has thrown up some problems.
当前问题是当你拖动 unitGroup
时它会触发 zoom
事件以及拖动
事件。
The current problem is that when you drag the unitGroup
it triggers the zoom
event along with the drag
event.
预期的行为是:
- 'click-and-drag'翻译x和y中的小的深灰色框尺寸。
- '鼠标滚轮'将小的深灰色框围绕其中心旋转。
这是一个Plunker:
Here is a Plunker: https://embed.plnkr.co/0GrGG7T79ubpjYa2ChYp/
推荐答案
实际上,你所看到的这是预期的行为。
Actually, what you are seeing here is the expected behaviour.
在D3中, d3.zoom()
不仅可以处理缩放,还可以处理平移同样。因此,鼠标移动由 d3.drag()
以及缩放功能处理。
In D3, d3.zoom()
handles not only the zoom but the panning as well. So, the mousemove is being handled by d3.drag()
and by the zoom function as well.
As Bostock(D3创造者)曾经说过:
As Bostock (D3 creator) once said:
最简单的解决方案就是检查你是否有真正的缩放(鼠标滚轮)在缩放功能中,如果你没有(没有鼠标滚轮),则返回:
Off the top of my head the simplest solution is just checking if you had a "real" zoom (mouse wheel) in the zoom function and, if you didn't (no mouse wheel), return:
if(!d3.event.sourceEvent.deltaY) return;
以下是您的更新内容:
Here is your plunker with that change only: https://plnkr.co/edit/jz5X4Vm9wIzbKmTQLBAT?p=preview
这篇关于D3变焦事件在Angular中拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!