昨天看了老外的视频教程,介绍了easeljs做canvas大大节约了开发的成本,老外用原生的canvas和easeljs 各实现了一遍方块旋转动画。
这时的我感觉很惊讶,原来动画做起来并不是我想得这么复杂,于是自己用模拟easeljs也做了一个动画旋转,感觉棒棒哒~
Easel Project
// 正规的createjs function initCreatejs() { var canvas = document.getElementById('easel'); var graphics = new createjs.Graphics(); var size = 100; graphics.beginFill('rgb(162, 216, 255)'); graphics.drawRect(0, 0, size, size); var shape = new createjs.Shape(graphics); //canvas center shape.x = canvas.width / 2; shape.y = canvas.height / 2; //graphics center shape.rotation = 30; shape.regX = size / 2; shape.regY = size /2 ; var stage = new createjs.Stage(canvas); stage.addChild(shape); stage.update(); } //仿造的createjs function initEric() { var canvas = document.getElementById('easel'); var graphics = new Graphics(); //图画 var shape = new Shape(graphics); //图形 var stage = new Stage(canvas).addChild(shape); //舞台 //设置图画 var size = 100; graphics.beginFill('rgb(162, 216, 255)'); graphics.drawRect(0, 0, size, size); graphics.regX = size / 2; graphics.regY = size / 2; //设置图形 shape.x = canvas.width / 2; shape.y = canvas.height / 2; shape.rotate = 30; //更新舞台 Ticker.setFPS(30); Ticker.addListener(function() { shape.rotate += 8; stage.update(); }); } function Ticker() { } Ticker.setFPS = function(num) { this.speed = 1000 / num; }; Ticker.addListener = function(cb) { setInterval(cb, this.speed); }; function Stage(canvas) { this.canvas = canvas; var context = this.context= canvas.getContext('2d'); }; Stage.prototype.showFrame = function() { var canvas = this.canvas; var context = this.context; context.strokeStyle = 'red'; context.strokeRect(0, 0, canvas.width, canvas.height); }; Stage.prototype.addChild = function(shape) { this.shape = shape; return this; }; Stage.prototype.update = function() { //通过stage实例顺藤摸瓜找到所有要用的对象 var canvas = this.canvas; var context = this.context; var shape = this.shape; var graphics = shape.graphics; context.save();//保存当前状态 context.clearRect(0, 0, canvas.width, canvas.height); //清空内容 context.fillStyle = graphics.color; context.translate(shape.x, shape.y); context.rotate(shape.rotate * Math.PI / 180); context.translate(-graphics.regX, -graphics.regY); context.fillRect(graphics.x , graphics.y , graphics.w, graphics.h); context.restore(); return this; }; function Shape(graphics) { this.x = 0; this.y = 0; this.graphics = graphics; } function Graphics() { this.regX = 0; this.regY = 0; } Graphics.prototype.beginFill = function(color) { this.color = color; return this; }; Graphics.prototype.drawRect = function(x, y, w, h) { this.x = x; this. y = y; this.w = w; this.h = h; return this; };