2014年4月19日土曜日

【Canvas】Ver5 ~ 跳ね返りアニメーション ~

Canvas 内の跳ね返りアニメーション描画

キャンバス内の四角形が跳ね返るアニメーション描画してみた


HTML




JavaScript

$(document).ready(function () {

    
    var can = document.getElementById('drawCanvas2');
    if (can.getContext) {

        
        var ctx1 = can.getContext('2d');
        var ctx2 = can.getContext('2d');

        
        var clearLoop = function () {
            ctx1.clearRect(0, 0, can.width, can.height);
            ctx2.clearRect(0, 0, can.width, can.height);
        }
    
        
        // 四角形サイズ
        var fillRectSize = 5;

        // 座標を乱数を使用して設定
        var randomValue = Math.floor(Math.random() * 100);
        
        // 四角形の座標位置
        var fillRectX1 = 0;
        var fillRectY1 = 0;
        var fillRectX2 = 0;
        var fillRectY2 = 0;
        
        // プラスマイナス補正値
        var turnValueX1 = 1;
        var turnValueY1 = 1;
        var turnValueX2 = Math.floor(Math.random() * 10);
        var turnValueY2 = Math.floor(Math.random() * 10);

        var drawLoop = function () {

            // 方向設定
            if (fillRectX1 < 0 || can.width < fillRectX1) {
                turnValueX1 *= -1;
            }
            if (fillRectY1 < 0 || can.height < fillRectY1) {
                turnValueY1 *= -1;
            }
            if (fillRectX2 < 0 || can.width < fillRectX2) {
                turnValueX2 *= -1;
            }
            if (fillRectY2 < 0 || can.height < fillRectY2) {
                turnValueY2 *= -1;
            }

            // 座標補正
            fillRectX1 += turnValueX1;
            fillRectY1 += turnValueY1;
            fillRectX2 += turnValueX2;
            fillRectY2 += turnValueY2;

            // 色を乱数を使用して設定
            var newColor = Math.floor(Math.random() * 0xFFFFFF).toString(16);
            
            // 描画
            ctx1.fillStyle = "#" + newColor;
            ctx1.fillRect(fillRectX1, fillRectY1, fillRectSize, fillRectSize);
            ctx2.fillStyle = "#" + newColor;
            ctx2.fillRect(fillRectX2, fillRectY2, fillRectSize, fillRectSize);
        }

        var timer;        //タイマー
        var delay = 5;    //タイマーを実行する間隔
        var loop = function () {

            // canvasクリア
            clearLoop();

            // 描画する
            drawLoop();

//            setInterval(loop, 100);
           
            //タイマー(一度クリアしてから再設定。)
            clearTimeout(timer);
            timer = setTimeout(loop, delay);
        }

        // 繰り返し関数呼び出し
        loop();

    }
});