angular - 如何通过 getBoundingClientRect 函数使用 async/await
问题描述
我的 Angular 应用程序出现错误,因为有时函数 getBoundingClientRect() 返回零。我发现它可能是一个异步操作。那么如何使这部分代码异步执行。在这种情况下如何使用 async/await?
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);
}
解决方案
推荐阅读
- python - PyOpenGL glDeleteBuffers 和 glDeleteVertexArrays 产生错误
- tabs - 添加 Buddypress 选项卡以显示成员(添加朋友选项卡)
- ios - 收到推送通知时,ReactNative 应用程序可能会在后台振动,但本机 iOS 应用程序(Swift)无法在后台振动
- python-3.x - 有没有办法提高 KivyMD MDDatatable 的效率?
- python - 如何确保反应来自用户而不是机器人本人?
- git - 如何在 Github 中添加检查以在拉取请求中查找 Jira id
- c++ - 多行的clang格式数组初始化器?
- laravel - 请求输入在中间件中返回 null
- r - 如何更改 R 中 effect_plot (jtools) 的间隔颜色?
- spring-boot - spring-boot升级后的404