繁体   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