views:

133

answers:

2

Hello, I'm trying to put an animated PNG dynamically from external .js file. First I found a simple animated png solution, which draws an animation wherever you put the code within <script> tags, but now it looks like I don't know how to call the function properly from external file.

The script is from AnimatedPNG, and it looks something like this:

<script type="text/javascript" src="animatedpng.js"></script>
<div id="pnganim" align="center">
    <script>
        fishAnim = new AnimatedPNG('fish', 't01.png', 3, 100);
        fishAnim.draw(false);
    </script>
</div>

Now, I'm trying to call this from external.js file and jQuery:

function addFish(){
    $('#pnganim').html('<script type="text/javascript" src="animatedpng.js" />');
    fishAnim = new AnimatedPNG('fish', 'fish01.png', 3, 100);
    myFish = fishAnim.draw(false);
    $('#pnganim').append(myFish);
}

... and it's not working. After I click a button that calls the addFish function, it opens only the first frame on a blank page.

What am I doing wrong here?

Thanks

A: 
  1. I don't know why you use $('#pnganim').html('<script ... />);.

    Just place this <script type="text/javascript" src="animatedpng.js"></script> in your <head>.

  2. $('#pnganim').append(myFish); doesn't make any sense. The draw function doesn't return a html element which could be appended to #pnganim

Instead your code probably should look like this

function addFish(){
    $('#pnganim').html('<script type="text/javascript">var fishAnim = new AnimatedPNG("fish", "fish01.png", 3, 100);fishAnim.draw(false);</script>');
}
jitter
That's what I've tried first, but it's not working neither. Firefox Error Console states issues in animatedpng.js itself, but animation works when write the <script> manually in html.Anyway, I give up on this concept, I'll try using animation with a single png file and sprites. Thank You very much for the answers.
Tomas
And what issues does it state? (Because I can see none in my console). Are you sure that the files fish01.png fish02.png and fish03.png exist in your directory? You could also try slightly modified source of AnimatedPNG I made (it's safer and shouldn't trigger any errors) http://pastebin.com/iW0tVK2E
jitter
A: 

Your js script propably is not loaded when you do the new ANimatedPNG thing. Try checking the console for error stating that AnimatedNG is not defined. You can fix this by using jQuery's AJAX script loading:

$.getScript('animatedpng.js', function(){
   fishAnim = new AnimatedPNG('fish', 'fish01.png', 3, 100);
   myFish = fishAnim.draw(false);
   $('#pnganim').append(myFish); //this line looks fishy too (chuckle)
});
Pim Jager