Clickable areas in SVG image that will lead to another image src

43 views Asked by At

Trying to create a point and click adventure game with SVG images and clickable path areas. For example, if you're in a hall way, and you click on a door, the img src will change to the next room corresponding with that door. I'm able to use addEventListener "click" and alert when the specific area is clicked. I just can't seem to get an idea on how to change the img src to the next room corresponding with that clicked area.

 //example img
<svg>
 <image xlink:href="/pointAndClickImg/Main Hall.svg"/>
 <path id="mainhall-left-door"/>
 <path id="mainhall-right-door/>
</svg>
 //example js that works with clicking and alerting
let mainHallLeftDoor = document.getElementById("leftdoor")
let mainHallRightDoor = document.getElementById("rightdoor")


mainHallLeftDoor.addEventListener("click", function() {
    alert("left door clicked")
    
})

mainHallRightDoor.addEventListener("click", function() {
    alert("right door clicked")
})
2

There are 2 answers

1
moon On

Image is a normal element and you can change all its attribute

mainHallLeftDoor.addEventListener("click", function() {
  alert("left door clicked")
  const img = document.querySelector('svg image')
  img.setAttribute('xlink:href', '/pointAndClickImg/room.svg')

})

0
Danny '365CSI' Engelman On

It will be easier to use one delegated event listener

<svg id=GAME viewBox="0 0 500 200" style="background:pink">
  <defs>
    <g id="room">
      <rect width="100" height="100" x="50" y="30" stroke="black" stroke-width="5"></rect>
    </g>
  </defs>
  <use href="#room" fill="red" />
  <use href="#room" fill="yellow" x="150" />
  <use href="#room" fill="blue" x="300" />
</svg>
<script>
  // GAME.addEventListener( "click" , func );
  // or, for just one click:
  GAME.onclick = (evt) => {
    let clicked = evt.target;
    if (clicked.hasAttribute("fill")) {
      GAME.style.background = clicked.getAttribute("fill");
    }
  }
</script>