将函数放入类中

时间:2014-05-28 03:36:36

标签: javascript arrays html5-canvas

我试图将多个功能放入一个类中。这样我就可以使用数组推出它了。但由于某些错误,我仍然无法将该功能推入阵列。我的程序是在画布中创建一个动画鱼精灵。为了进入下一步,我想在画布中添加更多鱼。

1 个答案:

答案 0 :(得分:0)

以下是鱼类“类”的快速简单示例。

演示:http://jsfiddle.net/m1erickson/jEznV/

Fish类像模板一样用于创建任意数量的Fish副本。

您可以像这样定义Fish类和属性:

// A Fish Class

function Fish(x,y,speedX,speedY,img){
    this.image=img;
    this.xPos=x;
    this.yPos=y;
    this.speedX=speedX||1;
    this.speedY=speedY||1;
}

您可以像这样定义Fish类的函数(称为方法):

// change the x/y position of this fish

Fish.prototype.move=function(){
    this.xPos+=this.speedX;
    this.yPos+=this.speedY;
};

// draw this fish on the canvas

Fish.prototype.draw=function(){
    context.drawImage(this.image,this.xPos,this.yPos);
};

您可以使用Fish类创建一个像这样的实际鱼类对象:

// create another fish using the Fish class

var anotherFish=new Fish(20,40,2,1,img);

你可以将所有的鱼放在一个阵列中:

// an array holding several instances of Fish objects
var fishes=[];

// create 3 new copies (instances) of Fish at random positions/speeds

for(var i=0;i<3;i++){
    var x=Math.random()*50-img.width;
    var y=i*img.height+25;
    var speedX=Math.random()*.25+.2;
    var speedY=.1;

    // create another fish using the Fish class
    var anotherFish=new Fish(x,y,speedX,speedY,img);

    // put this new fish into the fishes[] array
    fishes.push(anotherFish);

    // draw this new fish
    anotherFish.draw();

}

javascript类的教程超出了Stackoverflow答案的范围,但这应该可以让你开始。

[添加了图片预加载器的代码]

// image loader

var imageURLs=[];  // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("FishStrip.png");
imageURLs.push("moreFish.png");
imageURLs.push("evenMoreFish.png");
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[]
    // imgs[0] is FishStrip.png
    // imgs[1] is moreFish.png
    // imgs[2] is evenMoreFish.png

    // use the imgs[] to create your Fish instances now


}