Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.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 两种不同的图像加载_Javascript_Html_Canvas - Fatal编程技术网

Javascript 两种不同的图像加载

Javascript 两种不同的图像加载,javascript,html,canvas,Javascript,Html,Canvas,目前,每次运行动画时,我只加载一个图像 var imgFish = new Image(); imgFish.onload = init; imgFish.src = 'Image'; 我试图使两个或更多不同的图像加载在同一时间 当我按下“添加一条鱼”按钮时,只有一条橙色的鱼在画布上移动按钮我也想让更多不同的鱼在画布上游动。我创建了另一个按钮,名为“添加不同颜色的鱼!”,我想添加一条鱼,但使用相同代码的不同图像,以允许鱼在画布上显示动画 有人知道我怎样才能做到吗 这里有一个通用的图像加载程序,

目前,每次运行动画时,我只加载一个图像

var imgFish = new Image();
imgFish.onload = init;
imgFish.src = 'Image';
我试图使两个或更多不同的图像加载在同一时间

当我按下“添加一条鱼”按钮时,只有一条橙色的鱼在画布上移动按钮我也想让更多不同的鱼在画布上游动。我创建了另一个按钮,名为“添加不同颜色的鱼!”,我想添加一条鱼,但使用相同代码的不同图像,以允许鱼在画布上显示动画


有人知道我怎样才能做到吗

这里有一个通用的图像加载程序,它预加载所有图像,然后调用start

// image loader

// put the paths to your images in imageURLs[]
var imageURLs=[];  
// push all your image urls!
imageURLs.push("");

// the loaded images will be placed in images[]
var imgs=[];

var imagesOK=0;
loadAllImages(start);

function loadAllImages(callback){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
            imagesOK++; 
            if (imagesOK>=imageURLs.length ) {
                callback();
            }
        };
        img.onerror=function(){alert("image load failed");} 
        img.crossOrigin="anonymous";
        img.src = imageURLs[i];
    }      
}

function start(){

    // the imgs[] array now holds fully loaded images
    // the imgs[] are in the same order as imageURLs[]

}

您的代码需要一个image对象来在fish的构造函数中创建新的fish。因此,您需要做两件事:

首先,创建一个新的图像对象,指向不同颜色的鱼的不同图像

var imgFish2 = new Image();
imgFish2.onload = init;
imgFish2.src = 'https://dl.dropboxusercontent.com/s/0q7o0i23xmz719m/FishStrip.png';
其次,将函数绑定到函数init中的新按钮:

document.getElementById("button1").onclick = function() {
  // create another fish using the Fish class
  var anotherFish = new Fish(xPos, yPos, speedX, speedY, imgFish2, frameWidth, frameHeight);
  // put this new fish into the fishes[] array
  fishes.push(anotherFish) ;
  // make it start changing directions
  anotherFish.changeDirection();
  // draw this new fish
  anotherFish.drawFish();
}

问题在于第83行,Fish类现在使用this.image显示图像,而不是使用全局imgFish。谢谢,我现在理解了。您的代码没有任何帧速率控制,它在开始绘制Line 90时会请求下一帧。因此,下一个绘制事件的调用速度取决于浏览器。为请求下一帧时间添加setTimeout。有关示例,请参见。但是,由于每次调用绘制时代码都会移动鱼,因此如果浏览器决定不重新绘制,鱼的移动速度将非常慢。要正确地实现与速率无关的新动画,需要使用从回调传入的timestamp变量来计算要移动多少。