手順
以下の二つのファイル
- test.html
- test.js
を作成する
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>JavaScript Sample</title>
<script type="text/javascript" src="test.js"></script>
<script type="text/javascript">document.addEventListener('DOMContentLoaded', function(){main();});</script>
</head>
<body>
<div id="test_canvas"></div>
</body>
</html>
test.js
var main = function() {
var targetDiv = document.getElementById('test_canvas');
if (targetDiv == null) {
return;
}
var canvas = document.createElement("canvas");
canvas.height = 500;
canvas.width = 500;
targetDiv.appendChild(canvas);
ctx = canvas.getContext("2d");
if(ctx) {
var renderer = new Renderer(ctx, canvas.height, canvas.height);
renderer.render();
}
renderer.renderingObjects.push(new Rect);
renderer.render();
}
function Renderer(canvasCtx, width, height) {
this.ctx = canvasCtx;
this.width = width;
this.height = height;
this.renderingObjects = [];
this.render = function() {
for(i = 0; i < this.renderingObjects.length; i++) {
this.ctx.clearRect(0, 0, this.width, this.height)
this.renderingObjects[i].render(this.ctx);
}
window.requestAnimationFrame(this.render.bind(this));
}
}
function Rect(){
this.x = 0;
this.y = 0;
this.width = 100;
this.height = 100;
this.render = function(canvasCtx) {
if(canvasCtx) {
if(this.x > 400) {
this.x = 0;
}
++this.x;
textPosX = this.x + this.width;
textPosY = this.y + this.height;
canvasCtx.fillRect(this.x, this.y, this.width, this.height);
}
}
}
説明
連続的に描画を行いアニメーションを実現します。
定期的に画面を更新してもらえるように描画の管理をするRendererというオブジェクトを作成しました。
requestAnimationFrame
引数に関数オブジェクトを渡しておくとコールバックとして画面更新の直前に一度だけその関数を呼び出してくれます。
継続的に描画関数を呼び出してほしいので、引数にする関数オブジェクトの中で再度requestAnimationFrameに描画関数を渡しておきます。
bind
新しい関数オブジェクトを生成してくれます。
その関数オブジェクトの内部で使用するthisは引数に指定したオブジェクトに置き換わります。