I have been trying and trying to get my simple javascript script to move a bouncing ball to where a mouseclick event happened. I have the script here. It will interface with any canvas of any size with the id game. The ball bounces but it ignores mouseclicks. Do you know what’s wrong? Thanks.
var canvas;
var x, y;
var dx=4;
var dy=4;
var d = 20;
var width, height;
function init() {
canvasE = document.getElementById('game');
canvas= canvasE.getContext('2d');
width = canvasE.width;
height = canvasE.height;
x = d+dx+1;
y = d+dy+1;
canvasE.addEventListener("click", onClick, false);
clear();
canvas.beginPath();
canvas.fillStyle="#0000ff";
// Draws a circle of radius 20 at the coordinates 100,100 on the canvas
canvas.arc(x-1,y-1,d,0,Math.PI*2,true);
canvas.closePath();
canvas.fill();
setInterval(loop, 15);
}
function loop() {
clear();
canvas.beginPath();
canvas.fillStyle="#0000ff";
// Draws a circle of radius 20 at the coordinates 100,100 on the canvas
canvas.arc(x,y,d,0,Math.PI*2,true);
canvas.closePath();
canvas.fill();
// Boundary Logic
if( x<(d-dx)+1 || x>width-(d+dx)-1) dx=-dx;
if( y<(d-dx)+1 || y>height-(d+dy)-1) dy=-dy;
x+=dx;
y+=dy;
}
function clear() {
canvas.fillStyle="#ffffff";
canvas.fillRect(0,0,width,height);
canvas.fillStyle="#888888";
canvas.strokeRect(0,0,width,height);
}
function onClick(e) {
var clickX;
var clickY;
if (e.pageX || e.pageY) {
clickX = e.pageX;
clickY = e.pageY;
}
else {
clickX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
clickY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
clickX -= gCanvasElement.offsetLeft;
clickY -= gCanvasElement.offsetTop;
x = clickX;
y = clickY;
}
Here is more proper (though not 100% bulletproof) click code for you:
http://jsfiddle.net/4Lanc/
As a side note, using “canvasE and canvas” instead of “canvas and context/ctx” respectively for a naming convention might generate some serious confusion if you work along other canvas programmers. I would strongly suggest moving to “canvas and context/ctx”.