昨天看了老外的視頻教程,介紹了easeljs作canvas大大節約了開發的成本,老外用原生的canvas和easeljs 各實現了一遍方塊旋轉動畫。javascript
這時的我感受很驚訝,原來動畫作起來並非我想得這麼複雜,因而本身用模擬easeljs也作了一個動畫旋轉,感受棒棒噠~css
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Easel Project</title> <link rel="stylesheet" href="css/style.css" type="text/css" /> <script src="js/easeljs-0.8.2.combined.js" type="text/javascript"></script> <script src="js/script.js" type="text/javascript"></script> </head> <body onload="initEric();"> <canvas id="easel" width="380" height="480"> </canvas> </body> </html>
// 正規的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; };