问题描述
我正在从事Angular2项目.
I am working on a Angular2 Project.
class Coordinate {
x:number;
y:number;
}
class Data {
.....
coordinates: Array<Coordinate>;
.........
}
这是一个服务文件.我正在使用此服务访问组件的.ts文件中的数据.
This is a service file. I am using this service to access data in my Component's .ts file.
我想使用坐标数组在svg上绘制折线.在模板文件中,我尝试设置path元素的属性"d",但找不到正确的语法.
I want to use coordinates array to draw polyline on svg. In the template file, I am trying to set attribute 'd' of path element but can't figure out the right syntax to do so.
以下是该组件的.html文件的一部分
Following is the section of .html file of the component
<div>
<svg>
<path [[How am I supposed to set the d attribute here]]/>
</svg>
</div>
推荐答案
在Angular svg中需要进行一些特殊处理.这是关于此问题的非常好的文章: http://teropa.info/blog/2016/12/12/graphics-in-angular-2.html
In Angular svg requires some special treatment. This is a very good article about the issue: http://teropa.info/blog/2016/12/12/graphics-in-angular-2.html
现在,在您的情况下,模板中的名称应为:
Now in your case in the template it should be:
<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").
In your ts file you should add logic that results in path string (like for example yourVarThatStoresPathString = "M0,0 480,0 480,480 0,480 0,0").
因此,如果您有坐标(x,y)数组,则可能需要一个将其转换为这样的字符串的函数.同样在SVG中,还有其他字面量(字母)用于标识围绕M0,0之类的坐标的细节-意味着将铅笔移至0,0并开始绘图,或者在坐标可能意味着Z之后将Z链接-将最后一个坐标与第一个坐标链接.
So if you have array of coordinates (x,y) you might need a function that translates that into such a string. Also in SVG there are additional literas (letters) used to identify specifics around a coordinate like M0,0 - means move pencil to 0,0 and start drawing, or Z after the coordinate may mean - link this last coordinate with the first.
例如:
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-为方便起见,我使用的分隔符.
l = letters, s - spacer I use for convenience.
constructPath(pathPoints) {
let pathD = "";
pathPoints.forEach((coordinate) => {
pathD = pathD + coordinate.l + coordinate.x + "," + coordinate.y + item.s;
});
return pathD;
}
}
这当然是伪代码,但是应该给您一个方向.
This is of course a bit pseudo code but should give you a direction.
这篇关于如何在Angular 2中设置attribute d pf路径元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!