在javascript中为对象创建Click Listener

时间:2014-07-12 19:56:55

标签: javascript html

我有一些代码可以在javascript中创建一个弹跳球,这是我从教程中获得的。我要做的是为" ball"创建一个事件监听器。宾语。如果它是HTML中的一个元素,我会知道怎么做,但事实并非如此。我只想在点击球时弹出警报。这是我的代码。

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 个答案:

没有答案