javascriptsvgsetattribute

Simpler way to set attributes with svg?


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?


Solution

  • 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.