1,914 views
この記事は最終更新から 3164日 が経過しています。
CREATEJSを使ってJavaScriptでアニメーションをさせてみる。
公式サイトはこちら(↓) TOPページのアニメーションがとってもクールです。

■練習テーマ
まずは簡単なものから、ということで矩形枠内をボールが転がるアニメーションを作る。
壁に当たると時計回りに90度回転して跳ね返る。(処理簡略化のため物理法則とは異なる。)

実行サンプルはこちらです。
■プログラム
index.html
・6行目:CREATEJSを読み込む。
・7行目:自作のアニメーションスクリプトを読み込む。
・9行目:ページロード完了時にアニメーションを開始する。ID=viewの canvasに表示させる。
・15行目:アニメーションを表示する canvas を用意する。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//code.createjs.com/createjs-2015.05.21.min.js"></script>
<script src="./test.js"></script>
<script>
$(document).ready(function(){
var obj = new CjTest({id:'view'});
});
</script>
</head>
<body>
<canvas id="view" width="800" height="600" style="border:2px #000 solid;background:#ffe"></canvas>
</body>
</html>
test.js
自作のアニメーションスクリプト。
・30FPSでボールが canvas内を転がる。
・メソッドは3個 init(), makeBall(), movrBall()
・18行目:30FPSの周期処理を起動する。この中でボールの移動と描画更新を行う。
function CjTest(args){
this.init(args);
}
// prototype
CjTest.prototype = {
init: function(args){
// create stage
this.stage = new createjs.Stage(args.id);
// draw ball
this.canvas = $('#'+args.id);
this.stageWidth = this.canvas.attr('width');
this.stageHeight = this.canvas.attr('height');
this.makeBall();
// start animation
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener('tick', function(){
this.moveBall();
this.stage.update();
}.bind(this));
},
makeBall: function(){
// create sprite
this.sprite = new createjs.Shape();
// draw ball
this.ball_r = 10;
this.half_r = 5;
this.sprite.x = this.stageWidth / 2;
this.sprite.y = this.stageHeight / 2;
this.sprite.graphics.beginFill('#f00').drawCircle(0, 0, this.ball_r);
this.stage.addChild(this.sprite);
this.stage.update();
this.sprite.directionRad = 1;
},
moveBall: function(){
var x, y;
while(1){
x = this.sprite.x + Math.cos(this.sprite.directionRad) * 10;
y = this.sprite.y + Math.sin(this.sprite.directionRad) * 10;
if(this.half_r <= x && x < this.stageWidth - this.half_r &&
this.half_r <= y && y < this.stageHeight - this.half_r){
break;
}
this.sprite.directionRad = this.sprite.directionRad + (Math.PI / 4);
}
this.sprite.x = x;
this.sprite.y = y;
this.stage.update();
}
};
アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済2026-05-04: 0回 2026-05-03: 0回 2026-05-02: 0回 2026-05-01: 0回 2026-04-30: 0回 2026-04-29: 0回 2026-04-28: 0回