layabox学习记录

先定一个小目标:用JS开发一个小游戏

以下是一点要注意的地方:


不支持int


派发监听


sprite继承


目录结构

显示对象后添加在显示列表的,在最上层显示

用loadImage切换图片

//初始化舞台
Laya.init(1334, 750);
//需要切换的图片资源路径
this.monkey1 = "res/img/monkey1.png";
this.monkey2 = "res/img/monkey2.png";
//切换状态
this.flag = false;
//设置舞台背景色
Laya.stage.bgColor = "#ffffff";
this.img = new Laya.Sprite();
//显示绘制的图片(定义一个新图片)
switchImg();
//侦听switchImg中图片区域的点击事件,触发后执行switchImg切换图片
this.img.on(Laya.Event.CLICK,this,switchImg);  //
//添加到舞台
Laya.stage.addChild(img);
function switchImg(){
    //清空图片
    this.img.graphics.clear();
    //获得要切换的图片资源路径
    var imgUrl = (this.flag = !this.flag)? this.monkey1:this.monkey2;
    //加载显示图片,坐标位于100,50
    this.img.loadImage(imgUrl, 100, 50);
}

this.flag = !this.flag即this.flag=false !flag=ture时为monkey1
再次点击this.flag=flase时为monkey2
on

用drawTexture 加载显示图片

loadImage()方法可以即时加载外部图片资源,也可以从缓冲区读取图片资源,drawTexture()方法则必须先加载完图片后,再绘制添加到舞台中来,因此在示例代码中需要使用到加载(Laya.loader.load())与回调(Handler.create())的方法。

//初始化舞台
Laya.init(1334, 750);
//需要切换的图片资源路径
this.monkey2 = "res/img/monkey2.png";
//设置舞台背景色
Laya.stage.bgColor = "#ffffff";
//先加载图片资源,在图片资源加载成功后,通过回调方法绘制图片并添加到舞台
Laya.loader.load(this.monkey2,Laya.Handler.create(this,graphicsImg));
function graphicsImg(){
    var img = new Laya.Sprite();
    //获取图片资源,绘制到画布
    img.graphics.drawTexture(Laya.loader.getRes(this.monkey2),100,50);
    //添加到舞台
    Laya.stage.addChild(img);
}

用drawTexture 切换图片

//初始化舞台
Laya.init(1334, 750);
//需要切换的图片资源路径
this.monkey1 = "res/img/monkey1.png";
this.monkey2 = "res/img/monkey2.png";
//切换状态
this.flag = false;
//设置舞台背景色
Laya.stage.bgColor = "#ffffff";
//加载多张图片,在图片资源加载成功后,通过回调方法绘制图片并添加到舞台
Laya.loader.load([this.monkey1,this.monkey2],Laya.Handler.create(this,graphicsImg));
function graphicsImg(){
    //创建一个实例
    this.img = new Laya.Sprite();
    //添加到舞台
    Laya.stage.addChild(this.img);
    //显示初始化绘制的图片
    switchImg();
    //侦听switchImg中图片区域的点击事件,触发后执行switchImg切换纹理绘制
    this.img.on(Laya.Event.CLICK,this,switchImg);            
    //设置图片坐标s
    this.img.pos(100,50);
}
function switchImg(){
    //清空绘制
    this.img.graphics.clear();
    //获得要切换的图片资源路径
    var imgUrl = (this.flag = !this.flag)? this.monkey2:this.monkey1;
    //获取图片资源
    var texture = Laya.loader.getRes(imgUrl);
    //绘制纹理
    this.img.graphics.drawTexture(texture);                        
    //设置纹理宽高
    this.img.size(texture.width, texture.height);   
}

实现遮罩很简单,把创建的显示对象cMask作为遮罩对象赋值给img对象的mask属性,即实现了img显示对象的遮罩效果。

mask

还可以用组件直接实现

猜你喜欢

转载自blog.csdn.net/qq_40184652/article/details/81333442