JSFiddle - React, Tailwind, and code Playground

by dirkk0

HTML

<canvas id="background" width="640" height="480" class="canvas"></canvas>
    
        <canvas id="balls" width="640" height="480" class="canvas"></canvas> 

        <div class="score" id="score">Escaped Balls: <span><strong></strong></span></div>

CSS

.canvas { position: absolute; left: 0; top: 0; z-index: 0; }

.score { position: absolute; left: 10; top: 25; color: white; }

JavaScript

$(function() {

    var balls = document.getElementById("balls");

    var liveBalls = [];
    var escapedCount = 0;

    function drawBackground() {
        
        // get the context we are going to draw to
        var context = document.getElementById("background").getContext('2d');

        // set the beatiful beach background
        var img = new Image();
        img.src = 'http://dl.dropbox.com/u/19593893/CDN/beach.jpg';
        img.onload = function() {
            // draw the background to the canvas
            context.drawImage(img, 0, 0);
        }
    }

    function createBall() {
        // create the ball image
        image = new Image();
        image.src = 'http://dl.dropbox.com/u/19593893/CDN/ball.png';

        // push a new ball object into the liveBalls array
        liveBalls.push({
            image: image,
            x: Math.floor(Math.random() * 580),
            y: 640,
            index: 0,
            speed: Math.floor(Math.random() * 5)
        });
    }

    function draw() {

        var context = balls.getContext('2d');

        // clear the context to make sure we have a clean canvas
        context.clearRect(0, 0, 640, 480);

        // keep track of our escaped balls with this array
        var escapedBalls = [];

        // for each of our live balls, see if the ball is still on the canvas, if it is,
        // move it up by the random speed of the ball.
        $.each(liveBalls, function(index, value) {
            this.index = index;
            this.y -= this.speed;
            if (this.y > -64) {
                context.drawImage(this.image, this.x, this.y);
            }
            else {
                // the ball is off the screen so add it to the escaped balls
                // collection and increment the score
                escapedBalls.push(this);
                escapedCount++;
                $("#score span").text(escapedCount);
            }
        });

        // remove each of the escaped balls from...