简体   繁体   中英

Sprite PNG Javascript animation not working

I'm trying to create a Sprite animation using the following image: 在此处输入图片说明

To do so I am using it as a background and am trying to manipulate the background's position when animating. Somehow I can't get it working though - it shows the last frame from the very beginning.

Image: https://i.imgur.com/06vjVVj.png - 30800x1398 and 27 frames

Here's a codepen: https://codepen.io/magiix/pen/MWewdYo

#skull {
  position: absolute;
  border: 1px solid red;
  width: 1140px;
  height: 1398px;
  background: url("https://i.imgur.com/06vjVVj.png") 1140px 0;
}

const animateSkull = () => {
    const interval = 50;
    let pos = 30800 / 27;

    tID = setInterval(() => {
        document.getElementById("skull").style.backgroundPosition = `-${pos}px 0`;
        if (pos < 30800) {
            pos = pos + 1140;
        }
    }, interval);
};

If you check (with a console for example), you'll see that your animateSkull function is never called, because your addEventListener does not work. Change it to the following so it will be called (but your animateSkull function has another bug (or maybe your css I didn't checked) so it's not fully working after that but you should be able to fix that easily):

document.addEventListener('DOMContentLoaded', () => {
  animateSkull();
});

This should do the work, but the frames in your sprite don't have the same width. So the animation looks buggy. (that is one huge image just for the animation)

 const animateSkull = () => { const interval = 1000; let pos = -1140; tID = setInterval(() => { if (pos > -30800) { pos -= 1140; } document.getElementById("skull").style.backgroundPosition = `${pos}px 0`; }, interval); }; animateSkull();
 #skull { position: absolute; border: 1px solid red; width: 1140px; height: 1398px; background-image: url("https://i.imgur.com/06vjVVj.png"); background-position: -1140px 0; background-size: cover; } </style>
 <p id="skull"></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM