Search code examples
javascriptsprite-sheet

How to use sprite-sheets in JavaScript


Beginner here, I have failed to find a tutorial on this. I've got a page with game-mockups to test out different graphics. For now, I was using getElementByID phrase and using specific files. The more files I've got to test, the more tedious and time consuming it is.

I want to use a sprite-sheet (icons 16x16) where icons would display on the right panel and upon picking one, it would be pushed onto the mockup on the left. How do I do that?

https://i.sstatic.net/TEdK0.jpg

For now I was using this:

```
            <img class="testBubble" id="testBubble" src="imgNPC/b-bg/bbg-A3.gif" alt="image">

```
                    <div class="col-sm">
                        <img class="bgBublle" src="imgNPC/b-bg/bbg-A1.gif" onclick="bgbA1()">
                        <img class="bgBublle" src="imgNPC/b-bg/bbg-A2.gif" onclick="bgbA2()">
                        <img class="bgBublle" src="imgNPC/b-bg/bbg-A3.gif" onclick="bgbA3()">
                        <img class="bgBublle" src="imgNPC/b-bg/bbg-A4.gif" onclick="bgbA4()">
                        <img class="bgBublle" src="imgNPC/b-bg/bbg-A5.gif" onclick="bgbA5()">
                    </div>
//A
function bgbA1() {
    document.getElementById("testBubble").src="imgNPC/b-bg/bbg-A1.gif";
  }
function bgbA2() {
    document.getElementById("testBubble").src="imgNPC/b-bg/bbg-A2.gif";
  }
function bgbA3() {
    document.getElementById("testBubble").src="imgNPC/b-bg/bbg-A3.gif";
  }
function bgbA4() {
    document.getElementById("testBubble").src="imgNPC/b-bg/bbg-A4.gif";
  }
function bgbA5() {
    document.getElementById("testBubble").src="imgNPC/b-bg/bbg-A5.gif";
  }

```

Solution

  • I would recommend combining the sprite copy functions (bgbA1, bgbA2, etc.) into one function, which handles all the cases:

    <div class="col-sm">
        <img class="bgBublle" src="imgNPC/b-bg/bbg-A1.gif" onclick="bgb('A1')">
        <img class="bgBublle" src="imgNPC/b-bg/bbg-A2.gif" onclick="bgb('A2')">
        ...
    </div>
    
    //A
    function bgb(subSprite) {
        document.getElementById("testBubble").src="imgNPC/b-bg/bbg-"+subSprite+".gif";
    }
    

    It would also be a good idea to automate the creation of the images in .col-sm using document.createElement() and /*col-sm element*/.appendChild(/*created element*/)