canvasでボールが壁にぶつかって跳ね返る

スポンサーリンク

ボールが壁にぶつかって跳ね返る

動作ページはこちら

サンプルコード

<canvas id="myCanvas"  width="300" height="200" onclick="click1();"></canvas><br>

<script>
var music1 = new Audio('music/pon.mp3');
var music2 = new Audio('music/pi.mp3');
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 6;
var paddleHeight = 10;
var paddleWidth = 80;
var paddleX = (canvas.width-paddleWidth)/2;
var paddleY = (canvas.height-paddleHeight)/2;
var x = 30;
var y = 30;
var dx = 1;
var dy = -1;
var flg = false;

//canvasで最初にスタートの文字を中央揃え
var ctx = document.getElementById('myCanvas').getContext('2d');
ctx.font = "24px 'arial'";
var textWidth = ctx.measureText("Click Start!").width
ctx.fillStyle = "#ffffff";
ctx.fillText('Click Start!', (canvas.width - textWidth) / 2, canvas.height / 2);

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = "#fff";
    ctx.fill();
    ctx.closePath();
}

function drawPaddle() {
    ctx.beginPath();
    ctx.rect(paddleX,paddleY, paddleWidth, paddleHeight);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBall();
    drawPaddle();
    if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
        dx = -dx;
        music1.currentTime = 0;
        music1.play();
    }
    if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
        dy = -dy;
        music1.currentTime = 0;
        music1.play();
    }

    if(x + ballRadius > paddleX && x - ballRadius < paddleX + paddleWidth) {
      if(y + ballRadius > paddleY && y - ballRadius < paddleY + paddleHeight) {
        dy = -dy;
        music2.currentTime = 0;
        music2.play();
        ctx.fillStyle = "#FFFFFF";
        ctx.fill();
      }
    }
    x += dx;
    y += dy;
}

function click1(){
  //フラグを立ててクリック追加を防ぐ
  if (flg) return;
  flg = true;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  setInterval(draw, 10);
}
</script>
javascript
スポンサーリンク
のんびりブログ

コメント

タイトルとURLをコピーしました