使用PreloadJS加载图像并将它们添加到CreateJS阶段

Using PreloadJS to load images and adding them to CreateJS stage

本文关键字:添加 CreateJS 阶段 PreloadJS 加载 图像 使用      更新时间:2023-09-26

我试图在Javascript中创建一个三峰纸牌游戏,使用CreateJS来帮助与HTML画布进行交互。我对编程并不完全陌生,因为我在大学里学过Java和C,但我对Javascript和HTML都是新手。

我使用card类和Deck类创建了大量纸牌游戏,图像添加、事件监听和游戏逻辑都是在一个Javascript文件中完成的,但这导致了许多混乱、有些bug的代码,我觉得需要清理。

我试图实现一个单独的类卡表,这将是画布,或舞台,它将绘制4行可玩的卡,库存堆,和废物堆。我现在只是想让这堆存货在画布上显示出来,但这行不通。

我的问题是,为什么我的库存没有出现?此外,正如您所看到的,在创建卡片时正在加载卡片图像。我的做法应该有所不同吗?

卡类:

var Card = function(number) {
    this.isFaceUp = false;
    //number for image file path
    this.number = number;
    this.value = Math.ceil( (this.number)/4 );
    //back of the card is default image
    this.initialize("images/" + 0 + ".png");
    console.log("card created")
    this.height = this.getBounds().height;
    this.width = this.getBounds().width;
    //load the card's front image
    this.frontImage = new Image();
    this.frontImage.src = ( this.getImagePath() );
};
Card.prototype = new createjs.Bitmap("images/" + this.number + ".png");
Card.prototype.getImagePath = function() {
        return "images/" + this.number + ".png";
};
Card.prototype.getValue = function () {
    return this.value;
}
Card.prototype.flip = function() {
//    this.image = new Image();
//    this.image.src = ( this.getImagePath() );
    this.image = this.frontImage;
    this.isFaceUp = true;
};
Card.prototype.getHeight = function() {
    return this.height;
};
Card.prototype.getWidth = function() {
    return this.width;
};

CardDeck类:

function CardDeck() {
    //create empty array
    this.deck = [];
    //fill empty array
    for(i=1; i<=52; i++) {
        //fill deck with cards, with i being the number of the card
        this.deck[i-1] = new Card(i);
    }
    //shuffle deck
    this.shuffle();
}
CardDeck.prototype.getCard = function() {
    if(this.deck.length < 1) alert("No cards in the deck");
    return this.deck.pop();
};
CardDeck.prototype.getSize = function() {
    return this.deck.length;
};
CardDeck.prototype.shuffle = function() {
    for (i=0; i<this.deck.length; i++) {
      var randomIndex = Math.floor( Math.random()*this.deck.length );
      var temp = this.deck[i];
      this.deck[i] = this.deck[randomIndex];
      this.deck[randomIndex] = temp;
    }
};
CardDeck.prototype.getRemainingCards = function() {
    return this.deck.splice(0);
}
CardDeck.prototype.listCards = function() {
    for(i=0; i<this.deck.length; i++) {
        console.log(this.deck[i].number);
    }
};

CardTable类:

var CardTable = function(canvas) {
    this.initialize(canvas);
    this.firstRow = [];
    this.secondRow = [];
    this.thirdRow = [];
    this.fourthRow = [];
    this.stockPile = [];
    this.wastePile = [];
    //startX is card width
    this.startX = ( new Card(0) ).width*3;
    //startY is half the card height
    this.startY = ( new Card(0) ).height/2;
};
CardTable.prototype = new createjs.Stage();
CardTable.prototype.createStockPile = function(cards) {
    for(i=0; i<23; i++) {
        cards[i].x = 10;
        cards[i].y = 50;
        this.stockPile[i] = cards[i];
    }
};
CardTable.prototype.addToWastePile = function(card) {
    card.x = startX + card.width;
    card.y = startY;
    this.wastePile.push(card);
    this.addChild(card);
    this.update();
};
CardTable.prototype.drawStockPile = function() {
    for(i=0; i<this.stockPile.length; i++) {
        console.log("this.stockPile[i]");
        this.addChild(this.stockPile[i]);
    }
    this.update();
};
HTML文件:

<html>
    <head>
        <title>Tri-Peaks Solitaire</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://code.createjs.com/easeljs-0.8.1.min.js"></script>
        <script src="card.js"></script>
        <script src="carddeck.js"></script>
        <script src="cardtable.js"></script>
        <script>   
            function init(){
                var canvas = document.getElementById("canvas");
                var table = new CardTable("canvas");
                deck = new CardDeck();
                table.createStockPile(deck.getRemainingCards());
                table.drawStockPile();
                table.update();
            }
        </script>
    </head>
    <body onload="init()">
        <h1>Tri-Peaks Solitaire</h1>   
        <canvas style='border: 5px solid green; background: url("images/background.jpg");' 
                id="canvas" width="1000" height="450">
        </canvas> 
    </body>
</html>

PRELOADJS更新:

var canvas = document.getElementById("canvas");
        var stage = new createjs.Stage(canvas);
        var gameDeck = new CardDeck();
        var numbers = [];
        var preloader;
        var progressText = new createjs.Text("", "20px Arial","#FF0000");
        progressText.x = 50;
        progressText.y = 20;
        stage.addChild(progressText);
        stage.update();
        setupManifest();
        startPreload();
function setupManifest() {
            for(i=0; i<=52; i++) {
            console.log("manifest");
                manifest.push( {src:"images/" + i + ".png",
                                id: i} );
                numbers.push(i);
            }
        }
        function startPreload() {
            preload = new createjs.LoadQueue(true);
            preload.on("fileload", handleFileLoad);
            preload.on("progress", handleFileProgress);
            preload.on("complete", loadComplete);
            preload.on("error", loadError);
            preload.loadManifest(manifest);
        }
        function handleFileLoad(event) {
            console.log("A file has loaded of type: " + event.item.type);
            //console.log(numbers.pop());
            var cardNumber = numbers.pop();
            var newCard = new Card(cardNumber);
            //faces.push( new Image() );
            //faces[ faces.length - 1 ].src = "images/" + cardNumber + ".png";
            gameDeck.insertCard(newCard);
        }
        function loadError(evt) {
            console.log("error",evt.text);
        }
        function handleFileProgress(event) {
            progressText.text = (preload.progress*100|0) + " % Loaded";
            stage.update();
        }
        function loadComplete(event) {
            console.log("Finished Loading Assets");
        }

您只在创建卡片后立即更新舞台。卡正在加载位图图像,这是一个需要时间的并发操作。因此,渲染舞台的唯一时间是在图像加载之前。

我建议使用PreloadJS预加载你的卡图像。这也将给你更多的控制何时/如何加载,并让你在用户加载时显示进度条或干扰。

我建议等待所有的图像加载,然后调用stage.update()。或者使用createjs.Ticker.addEventListener("tick", handleTick);事件处理程序为您更新舞台。

参考:http://www.createjs.com/docs/easeljs/classes/Ticker.html