SVG:线条颜色

3

我有一个像这样的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;

};

这条线是这样创建的:g 是 SVG 文档。

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

在将颜色设置为红色的情况下,是否可以使用原始值而不是名称作为输入?例如:

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

我希望以这种方式设置颜色,因为我不想使用填充有精细颜色名称的数组,例如["red","black","blue"....],而是为我决定创建的任意行生成随机颜色。

2个回答

2

是的,您可以使用rgb、rgba和hex来设置颜色,如下所示:

Fill设置对象内部的颜色,而stroke设置绘制对象周围线条的颜色。您可以使用与HTML中相同的CSS颜色命名方案,无论是颜色名称(即红色),rgb值(即rgb(255,0,0)),十六进制值,rgba值等。

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


1
回答主要由链接组成并不有助于网站,因为链接随着时间的推移往往会失效。相反,复制一些相关信息,然后将链接留作信息来源。 - Ross
啊,原来如此简单,我以为唯一的赋值方式是通过 .style.stroke = colour; - 然而我现在的做法是通过 c_svgLine.setAttributeNS(null,"stroke",colour);。 - Ben Connor Hansell
1
@Ross 我已经更新了帖子,加入了来自源的相关信息。 - tipsqueal

2

有几件事情:

  1. 使用"rgb(255,60,245)"代替"255,60,45"
  2. 使用strokeWidth代替width

工作示例

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>


您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Ben Connor Hansell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接