问题
I have encountered a weird problem i have created a D3 tree which allows me to drag only after zoom otherwise it does not.I have tried @hostListerner
and event binding
but those things are outside D3 event hence these events are not working properly.
here is code please correct me id i am doing something wrong.
Initialization of D3 tree
displayTree() {
d3.json("./assets/flare.json").then(data => {
data = this.d3Object;
this.root = d3.hierarchy(data);
this.root.x0 = height;
this.root.y0 = 0;
let collapse = function(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
};
this.update(this.root);
});
const w = 2000;
const treeAdjustMent=-(this.heightNew/1.3);
let d={x:0,y:0};
//console.log("treeAdjustMent:::"+treeAdjustMent);
this.svg = d3
.select("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", this.heightNew + margin.top + margin.bottom)
.attr("viewBox", "0 1 " + w/0.7 + " " + this.heightNew*1.7)
.attr("overflow", "hidden")
.attr("padding", "50px")
.attr("id", "zoomableOf")
.call(this.dragHelper)
.on("click", function(d) {
d3.select("body")
.selectAll("div.tooltip1")
.remove();
})
.append("g")
.attr("id", "zoomable_id")
.attr("transform", "translate(900,"+treeAdjustMent+") scale(1.3,1.3)");
this.treeLayout = d3.tree().size([this.widthNew, this.heightNew]);
}
And zoom service
import { Injectable, EventEmitter } from '@angular/core';
import * as d3 from 'd3';
import {event, BaseEvent} from "d3-selection";
@Injectable({
providedIn: 'root'
})
export class D3ZoomService {
constructor() { }
applyZoomableBehaviour(svgElement, containerElement) {
let svg,g, container, zoomed, zoom;
svg = d3.select("svg");
svg = d3.select(svgElement);
g=d3.select("#zoomable_id");
//svgElement=eve.target;
container = d3.select(containerElement);
let duration = -1000;
let translateX,translateY,scaleX,scaleY,scale;
let transform;
zoomed = () => {
if(d3.event){
transform = d3.event.transform;
}else{
try {
transform = svgElement.attr("transform");
} catch (error) {
return;
}
}
// var offset = svgElement.getBoundingClientRect();
//var matrix = svgElement.getScreenCTM();
//coord= { x: (matrix.a * offset.x) + (matrix.c * offset.y) + matrix.e - offset.left,y: (matrix.b * offset.x) + (matrix.d * offset.y) + matrix.f - offset.top};
scaleX = transform.x;
scaleY = transform.y;
//relCoords = d3.mouse(d3.select('svg')[0]);
//scaleY=Math.min(coord.y,ZOOM_MAX.y);
//scaleY = coord.y;
g.transition().duration(duration).attr("transform", "translate(" + scaleX + "," + scaleY + ")scale(" + transform.k + ")")
.on("end", function(){
zoomed.call(zoom.transform, d3.zoomIdentity.translate(scaleX,scaleY).scale(transform.k))
});
}
zoom = d3.zoom().on('zoom', zoomed);
svg.call(zoom);
//return;
}
}
来源:https://stackoverflow.com/questions/58954149/d3-v5-tree-is-not-draggable-on-initialization-with-angular-7