Search code examples
javascriptanimationpnganimated-gif

Make a gif-like animation with a bunch of png files using JavaScript?


Despite all of my efforts to make a high quality gif-like animation out of a bunch of png files, I am still getting errors... I have gotten so many of them like "document.getElementById is not a function" and "Uncaught TypeError: Cannot set property 'src' of null". I decided to ask what I am doing wrong here. This is an old code that I found somewhere that I've been trying to use:

<script>

var min = 1;
var max = 12;
var current = min;

var keep_switching_icon = true;

function rotateIcon() {
  if (keep_switching_icon) {
    var nyanframe = document.getElementById('nyan')
    nyanframe.src = ({path:"nyan" + current + ".png"});
    console.log(current);
    if (current++ > max) {
      current = min;
    };

    window.setTimeout(rotateIcon, 300);
  }
}

rotateIcon();

</script>

<body>

<img src="nyan1.png" id="nyan"></img>

</body>

Solution

  • Try substituting nyanframe.src = "nyan" + current + ".png"; for nyanframe.src = ({path:"nyan" + current + ".png"});

    var min = 1;
    var max = 12;
    var current = min;
    
    var keep_switching_icon = true;
    
    function rotateIcon() {
      if (keep_switching_icon) {
        var nyanframe = document.getElementById('nyan');
        nyanframe.src = "nyan" + current + ".png";
        console.log(current);
        if (current++ > max) {
          current = min;
        };
    
        window.setTimeout(rotateIcon, 300);
      }
    }
    
    window.onload = rotateIcon;