2015-03-31 156 views
0

我有这样的SVG行变量,像这样:SVG:线条颜色

var c_line = function (x1, y1, x2, y2, color) { 

var c_svgLine = document.createElementNS(NS, "line"); 
c_svgLine.setAttributeNS(null, "x1", x1); 
c_svgLine.setAttributeNS(null, "y1", y1); 
c_svgLine.setAttributeNS(null, "x2", x2); 
c_svgLine.setAttributeNS(null, "y2", y2); 
c_svgLine.setAttributeNS(null, "class", "line"); 
c_svgLine.style.stroke = color; 
c_svgLine.style.width = 5; 
return c_svgLine; 

}; 

并线创建为这样:克,是SVG文件。

g.appendChild(c_line(50, 10, 100, 20,"red")); 

在将颜色设置为红色的情况下,是否可以使用名称red而不是使用名称red而将原始值用作输入?所以沿着线的东西:

g.appendChild(c_line(50, 10, 100, 20,"255,60,245")); 

我想设置颜色以这种方式,因为我不想拥有一个充满精致的颜色名称IE ["red","black","blue"....]一个数组,但随机生成的颜色然而,许多行,我决定创建。

回答

2

几件事情:

  1. 利用 “RGB(255,60,245)” 而不是 “255,60,45”
  2. 使用strokeWidth代替宽度

工作实例

var NS = 'http://www.w3.org/2000/svg'; 
 

 
var c_line = function (x1, y1, x2, y2, color) { 
 
    var c_svgLine = document.createElementNS(NS, "line"); 
 
    c_svgLine.setAttributeNS(null, "x1", x1); 
 
    c_svgLine.setAttributeNS(null, "y1", y1); 
 
    c_svgLine.setAttributeNS(null, "x2", x2); 
 
    c_svgLine.setAttributeNS(null, "y2", y2); 
 
    c_svgLine.setAttributeNS(null, "class", "line"); 
 
    c_svgLine.style.stroke = color; 
 
    c_svgLine.style.strokeWidth = 5; 
 
    return c_svgLine; 
 

 
}; 
 

 
var g = document.getElementById("g"); 
 
g.appendChild(c_line(50, 10, 100, 20, "rgb(0,60,245)")); 
 
g.appendChild(c_line(70, 10, 150, 10, "rgb(255,60,245)"));
<svg width="200px" height="200px" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" version="1.1"> 
 
    <g id="g"></g> 
 
</svg>

+0

我现在已经做到了:)>但感谢您的回复和精彩的回答!我也会采纳你的建议! – 2015-03-31 18:19:37

2

是的,你可以设置与RGB,RGBA和十六进制的颜色在这里看到:

填充设置对象内部的颜色和中风将围绕对象绘制的线条的颜色。无论是颜色名称(即红色),rgb值(即rgb(255,0,0)),十六进制值,rgba值等,您都可以使用您在HTML中使用的相同css颜色命名方案。

https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes

+1

主要包括链接答案不帮网站,链接倾向于去过时随着时间的推移。而是从链接中复制一些相关信息,然后将链接作为信息的来源。 – Ross 2015-03-31 18:12:10

+0

啊,这很简单,我只是通过.style.stroke = color来指定strkoe的唯一方法; - 但是我怎么做它是由c_svgLine.setAttributeNS(null,“stroke”,color); – 2015-03-31 18:17:52

+1

@Ross我用来源的相关信息更新了帖子。 – tipsqueal 2015-03-31 18:28:14