使用するクラス
HTMLCanvasElement
関数
- getContext(contextType)
CanvasRenderingContext2D
関数
- fillRect(x, y, width, height)
- fillText(text, x, y)
プロパティ
- fillStyle
- font
アニメーションの考え方
canvasでアニメーションを作るには、setInterval関数やrequestAnimationFrame関数などの一定時間毎に繰り返し描画処理を実行してあげます。canvasの内容を消して、新しく描く。canvasの内容を消して、新しく描く。これを短い間隔で繰り返しながら位置を変えてあげたり、大きさを変えたり、色を変えたりすることによって表現できます。
サンプル
文字列を動かすアニメーションのサンプルです。動く速さや文字列を変えると、サンプルのcanvasに反映されます。このサンプルでは文字列ですが、丸や四角などのアニメーションも簡単に作れます。
丸や四角などの図形の描画方法は「【javascript】canvasに丸や四角や文字などを描いてみよう」こちらの記事に書いてあります。
window.addEventListener( 'load', function(){
let canvas = document.querySelector('#sample-canvas70');
let context = canvas.getContext('2d');
context.font = "bold 20px 'Courier'";
let x = 0;
let y = 24;
let moveX = 0.6;
let moveY = 1;
let text = 'javascript';
let paddingX = text.length * 26 / 2;
let paddingY = 24;
function draw(){
context.fillStyle = 'rgba(255, 255, 255, 1)';
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = 'rgb(255, 120, 25)';
context.fillText(text, x, y);
x += moveX;
y += moveY;
if(x < 0)
moveX = Math.abs(moveX);
if(canvas.width - paddingX < x )
moveX = -Math.abs(moveX);
if(y < 0 + paddingY)
moveY = Math.abs(moveY);
if(canvas.height < y)
moveY = -Math.abs(moveY);
window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);
let moveXEle = document.querySelector('#move-x70');
let moveYEle = document.querySelector('#move-y70');
let canvasText = document.querySelector('#canvas-text70');
moveXEle.addEventListener('change', function(){
moveX = moveX < 0 ? -Math.abs(this.value / 10) : this.value / 10;
});
moveYEle.addEventListener('change', function(){
moveY = moveY < 0 ? -Math.abs(this.value / 10) : this.value / 10;
});
canvasText.addEventListener('change', function(){
text = this.value;
paddingX = text.length * 26 / 2;
});
});
横軸の動く速さ
縦軸の動く速さ
動いている文字
