LoginSignup
5
6

More than 5 years have passed since last update.

Canvasでバウンド?

Last updated at Posted at 2014-04-16
index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <style>#myCanvas {
  display: block;
}

    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="1000" height="500"></canvas>
    <!--button#startAnimation Start-->
    <!--button#stopAnimation Stop-->
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>(function(){
    $(function(){
        //キャンバス要素
        var canvas = $('#myCanvas');

        //2Dレンダリングコンテキスト
        var context = canvas.get(0).getContext('2d');

        var canvasWidth = canvas.width(); //キャンバス要素 幅
        var canvasHeight = canvas.height(); //キャンバス要素 高さ

        //矩形(x座標, y座標, 幅, 高さ, 回転時の半径, 回転時の角度)をまとめて管理するクラス
        var Shape = function(x, y, width, height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.radius = 150;
            this.angle = 0;
        };

        //複数の矩形を格納する配列
        var shape = new Shape(250, 250, 50, 50);

        var x = 0; var y = 0;

        //アニメーションループ
        function animate() {

            context.save();

            //矩形クリア
            context.clearRect(0, 0, canvasWidth, canvasHeight);

            //5°ずつ加算
            shape.angle += 5;

            //角度が360度を超えたら0度に戻す
            if (shape.angle > 360) {
                shape.angle = 0;    
            };

            x += 5;
            x %= 1000;
            y = shape.y+(shape.radius*Math.sin(shape.angle*(Math.PI/180)));

            //円の描画
            context.beginPath();
            context.arc(x, y, 50, 0, Math.PI*2, false);
            context.closePath();
            context.fill();

            context.restore();

            //アニメーションフラグが開始のとき
            setTimeout(animate, 1000/30);
        };
        //アニメーション初回スタート
        animate();
    });
})()
    </script>
  </body>
</html>
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6