簡體   English   中英

如何完全清除CreateJS代碼和畫布?

[英]How to clear CreateJS code and canvas completely?

我正在向DOM添加一個畫布,然后使用CreateJS來構建游戲。 我正在初始化CreateJS自動收錄器,並添加動畫和圖形。 一切正常,但只有一次。 如果我刪除畫布和游戲代碼,我以后不能再添加它 - 畫布只是不再顯示任何內容。

我的問題:如何從內存中正確清除所有CreateJS函數,並重新開始使用新畫布? 似乎CreateJS始終堅持使用舊的偵聽器和元素,即使我刪除了所有內容。

這是我的代碼:

// remove canvas and then restart - this causes buggy behavior
this.removeAndRestart = function() {
    document.getElementById("gamecontainer").innerHTML = '';
    createjs.Ticker.removeAllEventListeners();
    setTimeout(this.showGame, 1000);
}

// simply start the game - this works only the first time
this.showGame = function() {
        document.getElementById("gamecontainer").innerHTML = '<canvas id="gamecanvas" width="900" height="400"></canvas>';
        this.stage = new createjs.Stage("gamecanvas");

        // create the ticker and update the stage
        createjs.Ticker.setFPS(30);
        createjs.Ticker.addEventListener("tick", tickHandler);
}

如果要更改畫布或重置舞台,請確保從舞台中刪除DOM事件。 來自文檔:


enableDomEvents(布爾啟用)

啟用或禁用舞台添加到DOM元素(窗口,文檔和畫布)的事件偵聽器。 處理Stage實例時禁用事件是一種很好的做法,否則該階段將繼續從頁面接收事件。

更改canvas屬性時,必須禁用舊畫布上的事件,並在新畫布上啟用事件或鼠標事件將無法按預期工作。 例如:

myStage.enableDOMEvents(false);
myStage.canvas = anotherCanvas;
myStage.enableDOMEvents(true);

http://www.createjs.com/Docs/EaselJS/classes/Stage.html#method_enableDOMEvents

我不確定這是否能解決您的問題,但它可以提供幫助。

我建議你使用它

//create listener tick
createjs.Ticker.addEventListener('tick',tick);
//remove listener tick
createjs.Ticker.removeEventListener('tick',tick);
//exemple stopped object moves in Y axe if it exceeds heigth of canvas 
createjs.Ticker.addEventListener('tick',tick);
function tick(){
    console.log( myBitmap.x +" "+myCanvas.width);
    if (myBitmap.y < myCanvas.height){
        myBitmap.y=myBitmap.y+10;
    }else{
        createjs.Ticker.removeEventListener('tick',tick);
    }
    scene.update();
}

暫無
暫無

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

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