簡體   English   中英

如何將加載事件偵聽器添加到對象 javascript

[英]How to add a loading event listener to an object javascript

我目前正在開發一個帶有 javascript 精靈的游戲,我想添加一個事件偵聽器,用於在開始游戲之前檢查精靈圖像是否已加載。 我正在使用面向對象的編程,並且遇到了一些問題......我將展示一個我想到的例子:

function Sprite() {
    this.img = new Image();
    // either this:
    this.img.onload = function() {
    }
    // or this:
    this.img.addEventListener("load", function() {
        // Either way, when it loads, then it could proceed with the move or draw methods.
        // I don't even know how to do this yet...
    });

    this.img.src = "res/image.png";

    this.draw = function() {
        context.drawImage(//with all the parameters);
    }

    this.move = function() {
        // code that makes the sprites move
    }
}

無論哪種方式,以及我嘗試過的任何方式,它都無法正常工作而不顯示任何錯誤。 它只是不顯示精靈。 有誰知道發生了什么?

使用var self = this;使捕獲語義顯式var self = this; . 通過在名為self的變量中引用this ,您將能夠在 Sprite 的圖像加載函數中調用self.draw

問題可能是您在 onload 中嘗試this.draw ,但在這種情況下this指的是匿名函數而不是 Sprite。 請參閱下面的示例。

另外,我認為評論者的建議是您在加載圖像時出錯。 這是一個使用來自堆棧溢出使用的 CDN 之一的圖像的示例:

 var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); function Sprite() { var self = this; self.img = new Image(); self.draw = function() { context.drawImage(self.img, 0, 0); } self.move = function() { // code that makes the sprites move } // or this: self.img.addEventListener("load", function() { self.draw(); }); self.img.src = "https://cdn.sstatic.net/img/share-sprite-new.svg?v=78be252218f3g"; } var s = new Sprite();
 <canvas id="canvas" width="300" height="300"></canvas>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM