2014年4月19日土曜日

【Canvas】Ver4 ~ 四角形描画のアニメーション ~

アニメーション風の四角形描画

四角形アニメーションっぽく描画してみた


HTML




JavaScript

$(document).ready(function () {

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

        
        var ctx = can.getContext('2d');

        
        var clearLoop = function () {
            ctx.clearRect(0, 0, can.width, can.height);
        }

        
        // 四角形の座標サイズ
        var fillRectSize = 0;

        // プラスマイナス補正値
        var turnValue = 1;
            
        var drawLoop = function () {
            // 方向設定
            if (fillRectSize < 0 || can.width < fillRectSize) {
                turnValue *= -1;
            }

            // 色を乱数を使用して設定
            var newColor = Math.floor(Math.random() * 0xFFFFFF).toString(16);

            // 座標補正
            fillRectSize += turnValue;
            
            // 描画
            ctx.fillStyle = "#00C0C0";
            ctx.fillRect(0, 0, fillRectSize, fillRectSize);
        }

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

            // canvasクリア
            clearLoop();

            // 描画する
            drawLoop();

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

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

    }
});