Ben Connor Hansell
Ben Connor Hansell

Reputation: 188

SVG: Line Color

I have this SVG line variable like so:

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;

};

And the line is created as so: g, is the SVG document.

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

in the instance of setting the colour as red, is it possible instead of using the name red but rather the raw values as the input? so something along the lines of:

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

I'd like to set the colour in this way because i rather not have an array filled with refined colour names I.E ["red","black","blue"....] but generate random colours for however many lines i decided to create.

Upvotes: 3

Views: 1398

Answers (2)

tipsqueal
tipsqueal

Reputation: 203

Yes, you can set the color with rgb, rgba, and hex as seen here:

Fill sets the color inside the object and stroke sets the color of the line drawn around the object. You can use the same css color naming schemes that you use in HTML, whether that's color names (that is red), rgb values (that is rgb(255,0,0)), hex values, rgba values, etc.

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

Upvotes: 2

Harold Ship
Harold Ship

Reputation: 1019

A couple of things:

  1. use "rgb(255,60,245)" instead of "255,60,45"
  2. use strokeWidth instead of width

Working Example

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>

Upvotes: 2

Related Questions