创建JS函数添加到阶段

Create JS function add to stage

本文关键字:添加 JS 函数 创建      更新时间:2023-09-26

在createjs中,我尝试将元素添加到舞台,但仅在由函数调用时。

如果我将此代码添加到我的 onload init() 函数中,代码可以工作:

 function init()
{
 background = new createjs.Shape();
 background.graphics.beginLinearGradientFill(["blue", "darkgreen"], [0, 1], 0, 0, 100, 100).drawRect(0, 0, 70, 70);
 background.x = 0;
 background.y = 0;  
 stage.addChild(background);
}

但是,如果我像添加它一样

function init()
{
loadScreen();
}
function loadScreen()
{
background = new createjs.Shape();
 background.graphics.beginLinearGradientFill(["blue", "darkgreen"], [0, 1], 0, 0, 100, 100).drawRect(0, 0, 70, 70);
 background.x = 0;
 background.y = 0;  
 stage.addChild(background);
}

我可能只是在做一些愚蠢的事情,任何提示都值得赞赏。

谢谢

删除分号(;)After loadScreen() 函数防御

function init()
 {
  loadScreen();
 }
 function loadScreen()
 {
   background = new createjs.Shape();
    background.graphics.beginLinearGradientFill(["blue", "darkgreen"], [0, 1], 0, 0, 100, 100).drawRect(0, 0, 70, 70);
    background.x = 0;
    background.y = 0;  
    stage.addChild(background);

}

确保已

声明变量。

例如 var stage; var background;

并确保它们是全球性的。

window.onload = function(){
    var stage;
    var background;
    function init(){
        // create reference to stage and add 'tick' listener.
    }
    function loadScreen(){
        // draw something onto the stage.
    }
};

查看此网站的示例:http://createjs.com/docs/easeljs/modules/EaselJS.html。

我可以看到你删除了这一行->

 myGraphics.beginLinearGradientFill(["#000","#FFF"], [0, 1], 0, 20, 0,   120).drawRect(20, 20, 120, 120);

您是否尝试过在 init() 中实例化背景,然后将对象传递给 load 函数?