【问题标题】:d3js get corner coordinates of rectd3js获取矩形的角坐标
【发布时间】:2020-07-29 07:20:48
【问题描述】:

我正在尝试在两个矩形之间画线。我希望这条线从第一个矩形的中间到第二个矩形的中间。为此,我需要找到矩形的坐标。目前线的坐标是硬编码的,但这不是一个好方法。请帮忙,提前谢谢。

这是我的代码:

  const svgContainer = d3.select('body').append('svg')
      .attr('width', 1200)
      .attr('height', 8000);

    const A1 = svgContainer.append('rect')
      .attr('x', 10)
      .attr('y', 10)
      .attr('width', 550)
      .attr('height', 850)
   
    const A2 = svgContainer.append('rect')
      .attr('x', 680)
      .attr('y', 10)
      .attr('width', 550)
      .attr('height', 850)

 const lineA1ToA2 = svgContainer.append("line")
                       .attr("x1", 10)
                       .attr("y1", 270)
                       .attr("x2", 680)
                       .attr("y2", 270)
                       .attr("stroke-width", 2)
                       .attr("stroke", "black");
          

【问题讨论】:

    标签: javascript html angular d3.js


    【解决方案1】:

    javascript 和 svg 中没有“中心坐标”。所以你需要自己计算这些坐标。在您的情况下,最好的选择是将参数放入变量并根据它们计算所有坐标

    const x1 = 10, y1 = 10, width1 = 550; height1 = 850;
    const x2 = 680, y2 = 10, width2 = 550, height2 = 850;
        const A1 = svgContainer.append('rect')
          .attr('x', x1)
          .attr('y', y1)
          .attr('width', width1)
          .attr('height', height1)
       
        const A2 = svgContainer.append('rect')
          .attr('x', x2)
          .attr('y', y2)
          .attr('width', width2)
          .attr('height', height2)
    
     const lineA1ToA2 = svgContainer.append("line")
                           .attr("x1", x1 + width1 / 2)
                           .attr("y1", y1 + height1 / 2)
                           .attr("x2", x2 + width2 / 2)
                           .attr("y2", y2 + height2 / 2)
                           .attr("stroke-width", 2)
                           .attr("stroke", "black");
    

    也许有些变量是多余的,因为你重复了一些尺寸。只是为更一般的情况添加了它们

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2019-06-10
      • 2015-07-03
      相关资源
      最近更新 更多