user5491906
user5491906

Reputation:

Javascript and canvas issues

I am having an issue with my javascript not doing anything when the page loads here is my html and my javascript I am stumped I have no clue what the issue is(sorry for the poor spacing i did this on my iphone)

index.php

    <canvas id="breakout" width="480" height="320"></canvas>

   <script>

    var canvas =  document.getElementById("breakout") ;
    var ctx = canvas.getContext("2d");


    var x = canvas.width/2;
    var y = canvas.height-30;
    var mx = 2;
    var my = -2;

    function checkCollision{
    if(y + my < 0){
    my = -my;
    }
    if(y + my > canvas.height){
    my = -my;
    }
    if(x + mx > canvas.width-ballRadius){
    mx = -mx;
    }
    if(x + mx < ballRadius){
    mx = -mx;
    }
    }

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

    function drawing{
     ctx.clearRect(0,0,canvas.width,canvas.height);
     drawBall();
     x += mx;
     y += my;
     checkCollision();
      }

     setInterval(drawing,10);

    </script>

Upvotes: 0

Views: 82

Answers (1)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

You are not defining your functions properly. You need to define functions like so:

function foo() {
    ...
}

Doing:

function foo{
    ...
}

Is not valid and will lead to an error in the console. Also since ballRadius is being used in many functions, define it outside the function drawBall:

var x = canvas.width/2;
var y = canvas.height-30;
var mx = 2;
var my = -2;
var ballRadius = 10; // Added

var canvas =  document.getElementById("breakout") ;
var ctx = canvas.getContext("2d");


var x = canvas.width/2;
var y = canvas.height-30;
var mx = 2;
var my = -2;
var ballRadius = 10;

function checkCollision(){
    if(y + my < 0){
      my = -my;
    }
    if(y + my > canvas.height){
      my = -my;
    }
    if(x + mx > canvas.width-ballRadius){
      mx = -mx;
    }
    if(x + mx < ballRadius){
      mx = -mx;
    }
}

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

function drawing() {
     ctx.clearRect(0,0,canvas.width,canvas.height);
     drawBall();
     x += mx;
     y += my;
     checkCollision();
}

     setInterval(drawing,10);
<canvas id="breakout" width="480" height="320"></canvas>

Upvotes: 2

Related Questions