3

I am trying to set a background image to the svg circle through javascript.If I create SVG elements inside <body> and setting url to fill arrtibute for circle as below its working.

<script>          
    function changingImage(e) {
        e.currentTarget.setAttributeNS(null, "fill", "url(#img1)");
    } 
</script>

<body>
<svg height="100" width="100">

   <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="white" onmouseover='changingImage(event)'/>
   <defs>  
      <pattern id="img1" patternUnits="userSpaceOnUse"  width="100" height="100">
         <image  x="0" y="0" width="100" height="100" xlink:href="http://www.mysolutionzone.com/wp-content/uploads/Download-Nature-Sceneries-photos1.jpg" />
      </pattern>
   </defs>

</svg> 
</body>

But if I create all SVG elements in javascript its not working.Here is what I have.

<script>
 $(document).ready(function () {
            var defs = document.createElementNS("http://www.w3.org/2000/svg", "defs");
            var pattern = document.createElementNS("http://www.w3.org/2000/svg", "pattern");
            pattern.setAttributeNS(null, "id", "img1");
            pattern.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
            pattern.setAttributeNS(null, "height", "100");
            pattern.setAttributeNS(null, "width", "100");
            var image = document.createElementNS("http://www.w3.org/2000/svg", "image");
            image.setAttributeNS(null, "x", "0");
            image.setAttributeNS(null, "y", "0");
            image.setAttributeNS(null, "height", "100");
            image.setAttributeNS(null, "width", "100");
            image.setAttribute("xlink:href", "http://www.mysolutionzone.com/wp-content/uploads/Download-Nature-Sceneries-photos1.jpg");
            //var imageElement = $('<defs><pattern id="image1" x="0" y="0" patternUnits="userSpaceOnUse" height="1" width="1"><image x="0" y="0" xlink:href="http://www.mysolutionzone.com/wp-content/uploads/Download-Nature-Sceneries-photos1.jpg"></image></pattern></defs>');
            pattern.appendChild(image);
            defs.appendChild(pattern);
            $('svg').append(defs);
        });

        function changingImage(e) {
            e.currentTarget.setAttributeNS(null, "fill", "url(#img1)");
        }
</script>  
<body>
<svg height="100" width="100">

  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="white" onmouseover='changingImage(event)'/>
</svg
</body>

Is there another way to do this??

Swarna Latha
  • 1,004
  • 12
  • 21
  • 3
    See http://stackoverflow.com/questions/6893391/adding-image-namespace-in-svg-through-js-still-doesnt-show-me-the-picture/6902768#6902768 – Erik Dahlström Dec 11 '13 at 14:19

0 Answers0