核心Js代码:
var canvas, stage, container, w = window.innerWidth, h = window.innerHeight, s, dt = '';function init() { //设置canvas属性 canvas = document.getElementById('game'); canvas.width = w; canvas.height = h; //创建舞台 stage = new createjs.Stage(canvas); container = new createjs.Container();//绘制外部容器 stage.addChild(container); //创建矩形 s = new DrawPillars(); //注册事件 s.on('click', function () { alert(); }); //PS:Shape 类是没有getBounds这个方法,可以通过setBounds来获得 var bounds = s.getBounds(); //右下角控制矩形位置 s.x = w - bounds.width; s.y = h - bounds.height; //加入场景 container.addChild(s); stage.update();}//绘制矩形 类function DrawPillars() { createjs.Shape.call(this);//继承Shap类 this.graphics.beginFill("#ff0000").drawRect(0, 0, 50, 50); this.setBounds(0,0,50,50);//设置矩形的边界属性,这样可以获得width和height属性}DrawPillars.prototype = new createjs.Shape();//获得原型方法createjs.Ticker.setFPS(60);//设置游戏帧率createjs.Ticker.on("tick", tick);function tick() { if (s.x > 0 && s.x <= 10 && s.y > 0 && s.y <= 10) {//左上角 dt = 3; } else if (s.x > 0 && s.x <= 10 && s.y > h - s.getBounds().height - 10 && s.y <= h - s.getBounds().height) {//左下角 dt = 2; } else if (s.x > w - s.getBounds().width - 10 && s.x <= w - s.getBounds().width && s.y > 0 && s.y <= 10) {//右上角 dt = 1; } else if (s.x > w - s.getBounds().width - 10 && s.y > h - s.getBounds().height - 10 && s.y <= h - s.getBounds().height) { //右下角 dt = 0; } switch (dt) { case 0: s.x -= 5; break; case 1: s.y += 5; break; case 2: s.y -= 5; break; case 3: s.x += 5; } stage.update();}
说明讲解:
1:外部容器类
container = new createjs.Container();//绘制外部容器
一个容器是一种可嵌套的显示列表,允许您处理复合显示元素。例如你可以组的胳膊,腿,躯干和头部位图实例连接成一个容器,并把他们作为一个群体,同时还能够将各个部分之间的相互关系。
2:注册事件
//注册事件s.on('click', function () { alert();});
可以在显示对象上面绑定一个事件:可以用 on 或者addEventListener 注意大小写!包含(click,, mousedown,mousemove,mouseover)好像不支持,touchstart等!
3:创建一个矩形绘制类
//绘制矩形 类function DrawPillars() { createjs.Shape.call(this);//继承Shap类 this.graphics.beginFill("#ff0000").drawRect(0, 0, 50, 50); this.setBounds(0,0,50,50);//设置矩形的边界属性,这样可以获得width和height属性}DrawPillars.prototype = new createjs.Shape();//获得原型方法
4:PS:Shape类不拥有 getBounds方法,所以必须手动 setBounds ,边界,然后就可以获得 width|heigt属性;
5:游戏动画设置
createjs.Ticker.setFPS(60);//设置游戏帧率createjs.Ticker.on("tick", handleTick);
效果演示:
欢迎交流!