3

I have code that creates a bouncing ball in javascript, which I got from a tutorial. What I am trying to do is create an event listener for the "ball" object. I would know how to do it if it was a element in HTML, but its not. I just want an alert to pop up when the ball is clicked. Heres my code.

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

// Now setting the width and height of the canvas
var W = 350,
        H = 450;

// Applying these to the canvas element
canvas.height = H; canvas.width = W;

// First of all we'll create a ball object which will contain all the methods and variables specific to the ball.
// Lets define some variables first

    var ball = {},
        gravity = 1,
        bounceFactor = 0.7;

// The ball object
// It will contain the following details
// 1) Its x and y position
// 2) Radius and color
// 3) Velocity vectors
// 4) the method to draw or paint it on the canvas

    ball = {
    x: W/2,
    y: 50,

    radius: 30,
    color: "blue",

    // Velocity components
    vx: 0,
    vy: 1,

    draw: function() {

        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
        ctx.fillStyle = this.color;
        ctx.fill();
        ctx.closePath();
    }
    };

    function clearCanvas() {
    ctx.clearRect(0, 0, W, H);
}

    function update() {
    clearCanvas();
    ball.draw();

    ball.y += ball.vy;

    ball.vy += gravity;

    if(ball.y + ball.radius > H) {

        ball.y = H - ball.radius;
        ball.vy *= -bounceFactor;

    }
    }
    setInterval(update, 1000/60);
    bounceFactor = bounceFactor + 0.25;

0 Answers0