首页 > 解决方案 > 如何通过 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);
}

我的树连接器的样子

标签: angulartypescriptasynchronousasync-awaitcoordinates

解决方案


推荐阅读