Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  148] [ 3]  / answers: 1 / hits: 26295  / 11 Years ago, sun, january 26, 2014, 12:00:00

I'm new to SVG, so I apologize in advance for my ignorance.



I created a fiddle, just playing around with things. http://jsfiddle.net/a46p8/



var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width','200');
svg.setAttribute('height','200');


var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('width', '0');
line.setAttribute('height', '0');
line.setAttribute('x1', '0');
line.setAttribute('y1', '0');
line.setAttribute('x2', '150');
line.setAttribute('y2', '150');
line.setAttribute('stroke', 'rgb(255,0,0)');
line.setAttribute('stroke-width', '2');

svg.appendChild(line);

var ct = document.getElementById('container');
ct.appendChild(svg);


Is there really no simpler way to setAttributes? For example, is it at all possible to combine them with something like this:



line.setAttribute('x1', '0', 'y1', '0', 'x2', '150', 'y2', '150');


Yea, I know it doesn't work when I try in the fiddle. But is there some way to do it? If not, what's the reason why you can't?


More From » svg

 Answers
19

Writing your own function would be a solution. As for your example of line.setAttribute('x1', '0', 'y1', '0', 'x2', '150', 'y2', '150');, this would work, but it's going to be difficult to modify, and will expect that the parameters as passed in a particular order.



I would have a function that accepts a single object:



function Line(obj){
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
for(prop in obj) {
line.setAttribute(prop, obj[prop])
}
return line;
}

function SvgContainer(obj) {
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
for(prop in obj) {
svg.setAttribute(prop, obj[prop])
}
return svg;
}


So, all together it would look something like this:



var svgParent = new SvgContainer({
'width': 200,
'height': 200
});

var lineOne = new Line({
'width': 0,
'height': 0,
'x1': 0
// etc
});

var ctn = document.getElementById('container');
svgParent.appendChild(lineOne);
ctn.appendChild(svgParent);


If you're looking to go deeper then this and you need to do a lot of work with SVG in your project then a framework would probably be a worth considering.


[#72934] Friday, January 24, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidan

Total Points: 72
Total Questions: 95
Total Answers: 121

Location: Uzbekistan
Member since Sat, Feb 27, 2021
3 Years ago
aidan questions
Mon, Oct 11, 21, 00:00, 3 Years ago
Wed, Sep 29, 21, 00:00, 3 Years ago
Sun, Sep 5, 21, 00:00, 3 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;