【发布时间】:2018-01-25 23:30:52
【问题描述】:
我想在我的 D3 地图上添加缩放,但是当我单击一个节点时,拖放它,我的光标会修复所有元素。我添加了 .call(d3.zoom()) 但
来自 Angular 4 的代码组件:
ngOnInit(){
}
ngAfterViewInit(){
//this.svg = d3.select("svg");
this.svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.call(d3.zoom().on("zoom", function (event) {
let g = d3.select('svg > g');
g.attr("transform", d3.event.transform);
}))
.append("g");
let width = d3.select('svg').style("width");
let height = d3.select('svg').style("height");
width = width.substring(0, width.length - 2);
height = height.substring(0, height.length - 2);
this.color = d3.scaleOrdinal(d3.schemeCategory20);
this.simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
this.render(miserables);
}
ticked() {
this.link
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
this.node
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
render(graph){
this.link = this.svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line")
.attr("stroke-width", function(d) { return Math.sqrt(d.value); });
this.node = this.svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 5)
.attr("fill", (d)=> { return this.color(d.group); })
.call(d3.drag()
.on("start", (d)=>{return this.dragstarted(d)})
.on("drag", (d)=>{return this.dragged(d)})
.on("end", (d)=>{return this.dragended(d)}));
this.node.append("title")
.text(function(d) { return d.id; });
this.simulation
.nodes(graph.nodes)
.on("tick", ()=>{return this.ticked()});
this.simulation.force("link")
.links(graph.links);
}
dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
dragended(d) {
if (!d3.event.active) this.simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
dragstarted(d) {
if (!d3.event.active) this.simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
ngOnDestroy(){
}
如果我替换这个:
this.svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%");
通过这个:
this.svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.call(d3.zoom().on("zoom", function (event) {
let g = d3.select('svg > g');
g.attr("transform", d3.event.transform);
}))
.append("g");
缩放有效,但是当我选择要拖放的节点时出现问题,光标固定在所有元素上
【问题讨论】:
-
我对 Angular 一无所知,但我认为您可能在
drag和zoom之间存在事件冲突。当您拖动节点时,您需要添加一个dragstart事件并停止传播。祝你好运!
标签: javascript angular d3.js