【问题标题】:How to set attribute d pf path element in Angular 2?如何在 Angular 2 中设置属性 d pf 路径元素?
【发布时间】:2018-11-25 09:33:28
【问题描述】:

我正在开发一个 Angular2 项目。

  class Coordinate {
      x:number;
      y:number;
    }

    class Data {
     .....
     coordinates: Array<Coordinate>;
     .........
    }

这是一个服务文件。我正在使用此服务访问组件的 .ts 文件中的数据。

我想使用坐标数组在 svg 上绘制折线。在模板文件中,我试图设置路径元素的属性“d”,但无法找出正确的语法。

以下是组件的.html文件部分

<div>
 <svg>
  <path [[How am I supposed to set the d attribute here]]/>
 </svg>
</div>

【问题讨论】:

    标签: angular svg angular2-template


    【解决方案1】:

    在 Angular svg 中需要一些特殊处理。这是一篇关于这个问题的非常好的文章:http://teropa.info/blog/2016/12/12/graphics-in-angular-2.html

    现在在您的模板中应该是:

    <div>
     <svg viewBox="0 0 480 480" preserveAspectRatio="xMidYMid meet" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <svg:g>
          <svg:path [attr.d]="yourVarThatStoresPathString"></svg:path>
        </svg:g>
      </svg>
    </div>
    

    在您的 ts 文件中,您应该添加导致路径字符串的逻辑(例如 yourVarThatStoresPathString = "M0,0 480,0 480,480 0,480 0,0")。

    因此,如果您有坐标数组 (x,y),您可能需要一个函数将其转换为这样的字符串。同样在 SVG 中,还有一些额外的 literas(字母)用于识别坐标周围的细节,例如 M0,0 - 表示将铅笔移动到 0,0 并开始绘图,或者坐标后的 Z 可能意味着 - 将最后一个坐标与第一个坐标联系起来。

    举例:

    let pathPoints = [
                {
                    l: "M",
                    x: 135.00,
                    y: 245.00,
                    s: " "
                },
                {
                    l: "",
                    x: 135.00,
                    y: 110.00,
                    s: " "
                },
                {
                    l: "",
                    x: 345.00,
                    y: 110.00,
                    s: " "
                },
                {
                    l: "",
                    x: 345.00,
                    y: 245.00,
                    s: " "
                },
                {
                    l: "",
                    x: 345.00,
                    y: 380.00,
                    s: " "
                },
                {
                    l: "",
                    x: 135.00,
                    y: 380.00,
                    s: " "
                },
                {
                    l: "",
                    x: 135.00,
                    y: 245.00,
                    s: "Z"
                },
    ]
    

    l = 字母,s - 为方便起见我使用的间隔。

    constructPath(pathPoints) {
      let pathD = "";
      pathPoints.forEach((coordinate) => {
        pathD = pathD + coordinate.l + coordinate.x + "," + coordinate.y + item.s;
        });
      return pathD;
      }
    }
    

    这当然有点伪代码,但应该给你一个方向。

    【讨论】:

    • 谢谢。我试了两天。我使用的是插值 ... {{ yourVarThatStoresString}} 而不是 yourVarThatStoresString。
    猜你喜欢
    • 2016-08-06
    • 1970-01-01
    • 2012-03-13
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    相关资源
    最近更新 更多