1

I'm trying canvas for the first time and getting the motion I expect, but it's not clearing the previous position of the ball. I'm using beginPath() before each draw of the ball. So, I don't understand why it's not working. Any suggestions? Any and all help is much appreciated! Thank you!

window.onload = function(){

  var field = document.getElementById('field');
  var ctx = field.getContext('2d');

  var height = field.height;
  var width = field.width;

  //ball radius 
  var radius = 10


  //game speed 
  var gameSpeed = 2;

  //ball position 
  var ballx = 150; 
  var bally = 20;

  //ball speed
  var xBallSpeed = radius * 2;
  var yBallSpeed = radius * 2;

  //ball direction
  var xBallDir   = 1;
  var yBallDir   = 1;

  //player 
  var playerx = 50; 
  var playery = 180;
  var playerWidth = 40;
  var playerHeight = 20;

   //goal 
  var goalx = 50; 
  var goaly = 210;
  var goalWidth = 200;
  var goalHeight = 40;


  function draw() {

    //draw ball
    ctx.beginPath();
    ctx.fillStyle = "#000";
    ctx.arc(ballx, bally, radius, 0, Math.PI*2,false);
    ctx.fill();
    ctx.closePath();



    //draw goal
    ctx.beginPath();
    ctx.strokeStyle = "#000";
    ctx.rect(goalx, goaly, goalWidth, goalHeight); //y = field.height - goal.height
    ctx.closePath();
    ctx.stroke();


    //draw player
    ctx.beginPath();
    ctx.fillStyle = "#666";
    ctx.rect(playerx, playery, playerWidth, playerHeight); //y = field.height - goal.height
    ctx.closePath();
    ctx.fill();

    //change position of ball
    ballx = ballx + xBallSpeed + xBallDir;
    bally = bally + yBallSpeed + yBallDir;


    //does it hit the paddle? 
    //does it hit the goal?
    //does it hit the right, left or bottom wall?
  //   if(ballx >= width + radius) {
  //     xBallDir = -1;  
  //   }

  //   if(ballx <= width + radius){
  //     xBallDir  = 1; 
  //   }  
  // }

  setInterval(draw, gameSpeed); 
}
Hunter Turner
  • 6,804
  • 11
  • 41
  • 56
amack459
  • 23
  • 5

0 Answers0