ZoEM
ZoEM

Reputation: 852

Replacing an SVG with an image

I want to replace this SVG object with an image in the exact same position. There's probably a CSS way to go about it, but for a specific reason I'd much rather have this worked out entirely using Javascript!

<circle id="Sun" class="st0" cx="500" cy="300.8" r="30.3" onclick="changePic();"/>

This is the function that's probably in need of some tweaking.

function changePic(src)
{
        var im = document.getElementById("Sun"); 
        im.setAttribute("Sun",  "im");
        im.setAttribute("src", src || "img/picture.png");       
} 

"img/picture.png" is the folder and the image inside.

Also, is there a way in Javascript to call this function when the SVG is double clicked, as opposed to one click. I know it's not what I asked but I'd be grateful if I were helped out with that one too.

Upvotes: 1

Views: 1133

Answers (1)

0xdw
0xdw

Reputation: 3842

Try this

var svg = document.getElementById('Sun');

var src; // undefined

if (svg) {
  svg.addEventListener('click', function(event) {
    var img = document.createElement("img");
    img.setAttribute("Sun", "im");
    img.src = src || "img/picture.png";

    this.parentNode.replaceChild(img, this);
  }, false);
}
<!-- <circle id="Sun" class="st0" cx="500" cy="300.8" r="30.3" onclick="changePic();" /> -->

<svg id="Sun" class="st0" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="25" fill="#191919" />
</svg>

Upvotes: 2

Related Questions