dmerryman
dmerryman

Reputation: 11

Stringing together SVG path points using Javascript

I'm able to use the following JavaScript to create an SVG hexagon using some points generated from Inkscape:

var createHex = function(fill) {
    var NS = 'http://www.w3.org/2000/svg';
    var hexagon = document.createElementNS(NS, 'path');
    hexagon.setAttribute('d', 'm 311.5022,270.79644 62.8676,108.88986 -62.86759,108.88987 -125.73518,1e-5 -62.8676,-108.88986 62.86759,-108.88987 z');
    hexagon.setAttribute('fill', fill);
    hexagon.setAttribute('style', 'opacity:0.125');
    return hexagon;
}

Yet while attempting to have some Javascript math and string concatenation handle the point generation in the same fashion, the function fails to return anything:

var test = function(fill) {
    var NS = 'http://www.w3.org/2000/svg';
    var test = document.createElementNS(NS, 'path');
    var pt1x = 1 * 300;
    var pt1y = 0 * 300;
    var pt2x = (1/2) * 300;
    var pt2y = (sqrt(3)/2) * 300;
    var pt3x = (-1/2) * 300;
    var pt3y = (sqrt(3)/2) * 300;
    var pt4x = -1 * 300;
    var pt4y = 0 * 300;
    var pt5x = (-1/2) * 300;
    var pt5y = (-sqrt(3)/2) * 300;
    var pt6x = (1/2) * 300;
    var pt6y = (-sqrt(3)/2) * 300;
    test.setAttribute('d', 'm ' + pt1x + ',' + pt1y + ' ' + pt2x + ',' + pt2y + ' ' + pt3x + ',' + pt3y + ' ' + pt4x + ',' + pt4y + ' ' + pt5x + ',' + pt5y + ' ' + pt6x + ',' + pt6y + ' z');
    test.setAttribute('fill', fill);
    test.setAttribute('style', 'opacity:0.125');
    return test;
}

I'm new to both JavaScript and SVG; anybody able to tell me what I'm missing?

Upvotes: 1

Views: 280

Answers (1)

nkron
nkron

Reputation: 19791

Check your console log for errors. sqrt() is not a global JavaScript function. You want Math.sqrt().

Upvotes: 2

Related Questions