-1

Why is it that if I remove var framesPerSecond, the program runs fine? Even if I put the variable inside window.onload it doesn't work.

<canvas id="gameCanvas" width="800" height="600"></canvas>

<script>
var canvas;
var canvasContext;
var ballX = 50;
var ballSpeedX = 5;
var framesPerSecond = math.random()*(100-10)+10;
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
setInterval(callBoth, framesPerSecond);
}

function callBoth() {
  moveEverything();
  drawEverything();
}

function moveEverything() {
  ballX = ballX + ballSpeedX;
  if(ballX > canvas.width) {
    ballSpeedX = -ballSpeedX;
  }
  if(ballX < 0) {
    ballSpeedX = -ballSpeedX;
  }
}

function drawEverything() {
// canvas
  colorRect(0,0,canvas.width,canvas.height,'black');
// obstacles
  colorRect(40,40,720,520,'blue');
// car
  colorRect(ballX,100,10,10,'white');
}

function colorRect(leftX, topY, width, height, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.fillRect(leftX, topY, width, height);
}
</script>

Ps. I am just a beginner.

pgp
  • 83
  • 6
  • 1
    The console should tell you the problem. – Andreas Feb 04 '18 at 11:09
  • 2
    There was obviously no debugging attempt for this. "it doesn't work" isn't a descriptive issue. – Wright Feb 04 '18 at 11:10
  • I have never debugged anything before, I have no idea of how to go about it. – pgp Feb 04 '18 at 11:14
  • And a tipp for your `setInterval()` call. The second parameter tells the browser the **delay between two executions** of the function passed as the first parameter. – Andreas Feb 04 '18 at 11:15
  • [How can I debug my JavaScript code?](https://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code) – Andreas Feb 04 '18 at 11:15
  • Okay. Understood. – pgp Feb 04 '18 at 11:19
  • The question "how can I debug my javascript" has some outdated answers. Just press F12 and the developer tools of your browser should open. My favorite is [Chrome](https://developer.chrome.com/devtools) and used to hate having to debug something in IE but Edge got better (still prefer Chrome though). The developer tools console tab should have shown you the error. – HMR Feb 04 '18 at 11:35
  • I would also advice you to get vs code or atom as your ES editor, they will auto suggest some things that will prevent you from mis typing certain properties. – HMR Feb 04 '18 at 11:37
  • I am already using atom. – pgp Feb 20 '18 at 09:35

1 Answers1

1

Math should be capitalized: var framesPerSecond = Math.random()*(100-10)+10;

Orr Siloni
  • 1,268
  • 10
  • 21