Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript和png创建多个对象_Javascript_Animation - Fatal编程技术网

使用javascript和png创建多个对象

使用javascript和png创建多个对象,javascript,animation,Javascript,Animation,我正在尝试拍摄一组彗星坠落的宇宙飞船动画场景 //Create a comet div with img attached to it var cometScene = function(spaceNo){ var b = document.createElement('div'); b.id = 'cometio'; var cometImage = document.createElement('img'); cometImage.setAttribut

我正在尝试拍摄一组彗星坠落的宇宙飞船动画场景

//Create a comet div with img attached to it
var cometScene = function(spaceNo){
    var b = document.createElement('div');
    b.id = 'cometio';


    var cometImage = document.createElement('img');

    cometImage.setAttribute('src', 'images/comet1.png');
    b.appendChild(cometImage);

    document.getElementById('wrap').appendChild(b);
}

//Comet move
function cometMove(){
    var comet = document.getElementById('cometio');
    var pos = 0;
    var interval = setInterval(scene, 3);

    function scene(){
        if (pos === 1000){
            clearInterval(interval);
        } else {
            pos++;
            comet.style.top = pos + 'px';
            comet.style.left = pos + 'px';
        }
    }

    setInterval(scene, 3)
}
但是当我调用cometScene(3)函数时,我没有得到3个类似的对象。此外,这些对象如何在整个屏幕上分配,因为这只是一个div

function main(){
    var w = document.createElement('div');
    w.id = 'wrap';

    document.querySelector('body').appendChild(w);
    astronautScene();
    cometScene();
    shaceshipScene();
    cometMove();
    astronautMove();
}

这就是我要做的:

  • 给彗星一个类而不是id,因为它们可能会更多

  • 因为可以有多个循环,所以可以使用一个循环对它们进行迭代

  • 为了让他们能够自由移动,他们需要有
    位置:绝对
    或类似的东西

  • 不要对所有彗星的位置使用相同的变量,因为它们可能处于不同的位置

  • 要获得当前位置,只需将currect
    top
    left
    值解析为一个数字

  • //创建一个连接了img的comet div
    var cometScene=函数(spaceNo){
    var b=document.createElement('div');
    b、 className='cometio';
    var cometImage=document.createElement('img');
    setAttribute('src','images/comet1.png');
    b、 附加子对象(cometImage);
    document.getElementById('wrap').appendChild(b);
    }
    //彗星移动
    函数cometMove(){
    var comets=document.getElementsByClassName('cometio');
    for(设i=0;imain()
    您不应该多次使用ID(
    cometio
    ),而应该给它一个类现在为每个comet创建了
    scene()。这有点糟糕,但很有效。但是您应该尝试将其移出循环,并使用
    scene()
    谢谢,但是我使用了不同的方法。