1

I have an array of image variables that get preloaded using javascript to make an image sequence animation. The issue I have is setting the img element from HTML to use one of these images. It seems all the properies are strings?

Here's how I set the array of images in javascript:

for(var i = 0; i < 30; i ++){
    anim[i] = new Image();
    if(i < 10){
        anim[i].src = "images/anim/frame0" + i + ".png";
    }
    if(i >= 10){
        anim[i].src = "images/anim/frame" + i + ".png";
    }
}

and I simply have an ^img tag = "animation"^ in html that I want to change.

6
  • provide us some code samples please Commented Apr 7, 2017 at 11:59
  • How? Can you post your code in the question. Commented Apr 7, 2017 at 12:00
  • I would probably use some CSS keyframes for creating an animation if the images are not dynamically created or fetched from database. See: w3schools.com/css/css3_animations.asp You won't need javascript for that and it would be much faster and smoother Commented Apr 7, 2017 at 12:06
  • I'll check it out Commented Apr 7, 2017 at 12:08
  • My only concern with that is it's surely going to have to fetch the image every time I change the animation frame, with no preloading? Commented Apr 7, 2017 at 12:10

1 Answer 1

2

Your code looks valid.

for(var i = 0; i < 30; i++){
    anim[i] = new Image();

    if(i < 10){
        anim[i].src = `images/anim/frame0${i}.png`;
    }

    if(i >= 10){
        anim[i].src = `images/anim/frame${i}.png`;
    }
}

Now you can do: document.body.appendChild(anim[0]);

I tested this and it works for me.

If you want to change src on the fly then you'd have to select the appended element and update its src like this: document.querySelectorAll('img')[0].src = newSourceVariable;.

Sign up to request clarification or add additional context in comments.

5 Comments

oh awesome, and i'll need to delete the old image object right?
is there any way to just replace the old image? It has some properties that I need it to keep, as well as a parallax scroll function that uses the original object.
Yes, either delete the old image (not recommended because you'll have flickering animation) or update the src by selecting the already appended image. With jQuery you'd do $('img').eq(0).attr('src', newSource); to replace the src of already existing image.
With pure JS you'd do: document.querySelectorAll('img')[0].src = newSourceVariable; - it will select the appended image and replace the src of already existing image. You can do this in a loop as well.
So after a few more days of trying I've got it working using AppendChild. Thanks bud :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.