Set HTML <img> element to Javascript image variable

安稳与你 提交于 2019-12-12 04:01:35

问题


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.


回答1:


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;.



来源:https://stackoverflow.com/questions/43277566/set-html-img-element-to-javascript-image-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!