Search code examples
javascriptsvggoogle-visualizationappendchild

appendChild to SVG defs to create Image Background in Marker for Geochart API


I'm trying to tweak a bit the google chart api so I can change the default round marker, with an image. I'm thinking of doing this by setting an image pattern for the svg circle to use. I should be close, but it doesn't seem to work for some reason.

Full code here: http://jsfiddle.net/PVkbM/1/

Here's part of the code.

google.visualization.events.addListener(chart, 'ready', function () {


    var patt = document.createElement('pattern');
    patt.setAttribute('id', 'img1');
    patt.setAttribute('patternUnits', 'userSpaceOnUse');
    patt.setAttribute('width', '20');
    patt.setAttribute('height', '20');
    patt.setAttribute('x', '0');
    patt.setAttribute('y', '0');


    var image = document.createElement('image');
    image.setAttribute('xlink:href', 'https://www.google.com/images/srpr/logo3w.png');
    image.setAttribute('x', '0');
    image.setAttribute('y', '0');
    image.setAttribute('width', '24');
    image.setAttribute('height', '24');

    var defs = document.getElementsByTagName('defs')[0];

    patt.appendChild(image);
    defs.appendChild(patt);

    //This works
     //document.getElementsByTagName('circle')[0].setAttribute("fill", "#FFF");     

  document.getElementsByTagName('circle')[0].setAttribute("fill", "url(#img1)");

 });    

 chart.draw(data, options);

From what I can see, the code adds the new < pattern > inside the < defs >, but it doesn't work. Am I missing something?


Solution

  • image.setAttribute('xlink:href', 'https://www.google.com/images/srpr/logo3w.png');

    needs to be

    image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'https://www.google.com/images/srpr/logo3w.png');

    You also need to create elements in the SVG namespace e.g.

    var image = document.createElement('image');

    should be

    var image = document.createElementNS('http://www.w3.org/2000/svg', 'image');

    and the pattern too.

    http://jsfiddle.net/PVkbM/34/