我在Angular应用程序中遇到错误,因为有时函数getBoundingClientRect()返回零。我发现这可能是异步操作。因此,如何使这部分代码异步执行。在这种情况下如何使用异步/等待?
let right = document.getElementById(rightId);
let rightPosition = right.getBoundingClientRect()
x_right = mainBox.width;
y_right = rightPosition.top - mainBox.top + rightPosition.height/2;
我正在使用SVG路径在两个Angular Material树组件之间绘制连接线。
这是我创建svg的方法:
createSVG() {
let svgContainer = document.getElementById('svg-main-container');
this.svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
this.svg.setAttribute('id', 'svg-canvas');
this.svg.setAttribute('style', `position:absolute;left:0;top:0;display:inline-block;height:100%;width:100%`);
this.svg.setAttribute('viewBox', '0 0 100 100');
this.svg.setAttribute("preserveAspectRatio", "none");
this.svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
svgContainer.appendChild(this.svg);
this.svgService.svg = this.svg;
return this.svg;
}
我如何连接元素
connectDivs(leftId, rightId) {
let svgContainer = document.getElementById('svg-component');
let mainBox = svgContainer.getBoundingClientRect();
let points = [];
//left element
let left = document.getElementById(leftId);
let leftPosition = left.getBoundingClientRect();
let x_left = 0;
let y_left = leftPosition.top - mainBox.top + leftPosition.height/2;
points.push({x_left, y_left});
//right element
let right = document.getElementById(rightId);
let rightPosition = right.getBoundingClientRect();
let x_right = mainBox.width;
let y_right = rightPosition.top - mainBox.top + rightPosition.height/2;
this.drawConnector(points[0], points[1]);
}
这是我绘制连接路径的方式:
drawConnector(a,b){
let path = document.createElementNS("http://www.w3.org/2000/svg", "path");
let d = `M${a.x_left},${a.y_left} C50,${a.y_left} 50 ${b.y_right} ${b.x_right} ${b.y_right}`;
path.setAttributeNS(null, "d", d);
path.setAttributeNS(null, "fill", "none");
path.setAttributeNS(null, "stroke", "#555");
path.setAttributeNS(null, "stroke-width", "1.5px");
path.setAttributeNS(null, "vector-effect", "non-scaling-stroke");
path.setAttribute("id", this.svgService.draggedElementId);
path.setAttribute("class", this.svgService.draggedElementId);
this.svgService.svg.appendChild(path);
}