marcwoozie blog

都内のwebエンジニア2年目です

宅配便が来るまで暇なのでcanvasの練習しました。

今日は午前中の8時〜12時までの間に宅配便が届くとの事だったので8時から起きてるけど
なかなか来なくて暇なので昨日ドットインストールで見てたcanvasを使って遊んでみました。

壁にあたったら跳ね返るよくありそうなやつです。


<!doctype html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Canvas</title>
</head>
<body>

  <canvas style="width: 400px; height: 200px; border: 1px solid gray;" id="canvas"></canvas>

<script>
;(function(){

  var canvas, ctx;
  var x = 0;
  var y = 0;
  var radius = 6;
  var gx = true;
  var gy = true;

  var init = function(){
    canvas = document.getElementById("canvas");
    if( !canvas || !canvas.getContext ) return false;
    ctx = canvas.getContext("2d");
    ctx.fillStyle = "rgba(000, 000, 000, .6)";

    (function roop(){
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      if( x >= canvas.width - radius ) gx = false;
      if( y >= canvas.height - radius ) gy = false;
      if( gx ){
        x++;
      } else {
        x--;
        if( x <= radius ) gx = true;
      }
      if( gy ){
        y++;
      } else {
        y--;
        if( y <= radius ) gy = true;
      }
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, Math.PI*2, false);
      ctx.closePath();
      ctx.fill();
      setTimeout(roop, 1);
    })();

  };

  window.onload = function(){
    init();
  };

})();

</script>

</body>
</html>


完全に今更!?ですがcanvasすごい楽しいので、ハマりそうです。