Simple Ball on Canvas

by brouser

HTML

<!-- HTML code for header1 and canvas elements -->
<h1>Simple animated ball on black background</h1>
<canvas id = "myCanvas" width = "800" height = "600">
Sorry, your browser doesn't support canvas elements!
</canvas>

CSS

/* Create CSS selectors and provide attributes */
canvas{
  border: 3px dotted blue;
}

JavaScript

/* JavaScript */

// Always need these two variables, their values will be assigned later.
var canvas;
var ctx;

// set the initial ball position
var ball_x_position = 50;
var ball_y_position = 50;

// set the initial speed (distance it will travel each setInterval() cycle)
var ball_x_speed = 5;
var ball_y_speed = 7;

// This function calculates the new position of each graphic element for
// each setInterval() cycle.
function calculateNextPosition() {
    // ball x speed is added to ball x position to give new ball x position.
    ball_x_position += ball_x_speed;
    
    // ball y speed is added to ball y position to give new ball y position. 
    ball_y_position += ball_y_speed;
    
    // We can use the console to look at the x, y positions each setInterval() cycle.
    //console.log(ball_x_position);
    //console.log(ball_y_position);    
    
    // collision on right wall
    if(ball_x_position > canvas.width) {
        ball_x_speed *= -1;
    }
    // collision on left wall
    if(ball_x_position < 0) {
        ball_x_speed *= -1;
    }
    // collision on bottom wall
    if(ball_y_position > canvas.height) {
        ball_y_speed *= -1;
    }
    // collision on top wall
    if(ball_y_position < 0) {
        ball_y_speed *= -1;
    }
}

// This function draws all the elements in their calculated positions each
// setInterval() cycle.
// Note the black background doesn't move but is redrawn every time.
function drawAllElements() {
    // Make black background size of full canvas
    makeFillColorRect(0, 0, canvas.width, canvas.height, "black");
    
    // Draw ball for each value of ball_x_position
    makeFillColorCircle(ball_x_position, ball_y_position, 10, "blue");
}

// This function loads all the code into memory, then starts up setInterval() to run
// a certain frame rate to recalculate element position and draw them each cycle.
window.onload = function() {
    // our two important canvas variables are assigned values.
    canvas =...