Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change the image pattern in SVG using Javascript

How can I dynamically change/add an image pattern into an existing SVG on my page using Javascript? Or any library.

This is what I've got so far..

function addSvgStuff(svg, id) {

    var svgNS = svg.namespaceURI;
    var pattern = document.createElementNS(svgNS, 'pattern');

    pattern.setAttribute('id', id);
    pattern.setAttribute('patternUnits', 'userSpaceOnUse');
    pattern.setAttribute('width', 500);
    pattern.setAttribute('height', 500);

        var image = document.createElementNS(svgNS, 'image');
        image.setAttribute('xlink:href', 'http://www.jampez.co.uk/sensoryuk/events/test.jpg');
        image.setAttribute('x', -100);
        image.setAttribute('y', -100);
        image.setAttribute('width', 500);
        image.setAttribute('height', 500);

    pattern.appendChild(image);

    var defs = svg.querySelector('defs') ||
    svg.insertBefore( document.createElementNS(svgNS,'defs'), svg.firstChild);

    $('svg polygon').attr('fill', 'url(#' + id + ')');

    return defs.appendChild(pattern);
}
like image 411
Daniel Hill Avatar asked Nov 14 '12 12:11

Daniel Hill


1 Answers

You neeed to use setAttributeNS to set attributes that are in the xlink namespace so

    image.setAttribute('xlink:href', 'http://www.jampez.co.uk/sensoryuk/events/test.jpg');

should be

    image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'http://www.jampez.co.uk/sensoryuk/events/test.jpg');
like image 164
Robert Longson Avatar answered Sep 27 '22 23:09

Robert Longson