AngularJS
先週ぐらいからAngularJSを本格的に勉強始めました。
AngularJSの記事を何本か書きました。
Angular.js学習メモ vol.01
http://qiita.com/kenjiSpecial@github/items/72074e89762556a105e4
AngularJSの学習メモ Directiveについて
http://qiita.com/kenjiSpecial@github/items/c99198406e93916f9ba0
AngularJSでよく見るDependency Injectionについて
http://qiita.com/kenjiSpecial@github/items/6b7db5591bb2684058d5
ArduinoとNode.jsで室内温度計を作るまで、、vol.02
http://qiita.com/kenjiSpecial@github/items/2f6337d6cd3f33975c20
DOMとかにはかなり威力を発揮できるのはわかったのですが、果たしてCanvasアニメーションはどうなのかというところが謎でした
Canvasアニメーション
Canvasアニメーションではloopでフレーム毎に計算し、レンダリングを更新するのが重要です。
function draw(){
// 計算
// CanvasApiで描画
requestanimationframe(draw);
}
draw();
drawをひたすら回し続けます。
AngularJSでCanvasアニメーション
理想をいうとControllerをマイフレームを呼び出したいのですが、それはできなさそう、、
今回は力技で攻めました。。
<body ng-app="animation01App" ng-controller="CanvasCtrl">
<canvas></canvas>
</body>
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
angular
.module('animation01App', []);
angular.module('animation01App')
.controller('CanvasCtrl', ['$scope', '$document', function($scope, $document){
//var canvas = $document;
var canvas = $document.find('canvas')[0];
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
var x = 0;
var y = 0;
function draw(){
x += 1;
y += 1;
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
ctx.fillStyle = "#ffffff";
ctx.beginPath();
ctx.arc(x, y, 10, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();
requestAnimationFrame(draw);
}
draw();
}]);
controller内にdraw関数を作成して、controllerが呼び出されたら、draw関数を呼び出します。
一度呼び出したら、ひたすら呼び出し続けると行った感じです。
codepenにアップしたので、こちらをみてください。。
See the Pen Angular Canvas Animation by Kenji Saito (@kenjiSpecial) on CodePen.
もっといい方法を模索したいです。