0

I'm trying to teach myself how to get the x and y co-ordinates clicked in a canvas to write games with. The code I've written has a subtle bug I can't figure out. When you click on the canvas, the ball moves roughly to where you clicked. But I want it centred on where I click. Instead that point is in the upper left corner of the new ball.

(I've edited the code to work correctly by using subtracting canvas.offsetLeft from the returned event.clientX and canvas.offsetTop from event.clientY, two properties I wasn't aware of until pointed to a similar post.)

var canvas, context, ball_pos;

var BALL_RADIUS = 15;

function start() {
    'use strict';
    canvas = document.getElementById('c');
    context = canvas.getContext('2d');
    ball_pos = [canvas.width / 2, canvas.height / 2];
}

function draw() {
    'use strict';

    // draw background
    context.fillStyle = "rgb(248,248,248)"; // off white
    context.fillRect(0, 0, canvas.width, canvas.height);

    // draw ball
    context.strokeStyle = 'black';
    context.lineWidth = 1;
    context.fillStyle = 'red';
    context.beginPath();
    context.arc(ball_pos[0], ball_pos[1], BALL_RADIUS, 0, Math.PI * 2, true);
    context.closePath();
    context.fill();
    context.stroke();
}

function animate() {
    'use strict';
    window.requestAnimationFrame(animate);
    draw();
}

function click(evt) {
  ball_pos[0] = evt.clientX - canvas.offsetLeft;
  ball_pos[1] = evt.clientY - canvas.offsetTop;
}

// register event handlers
window.onclick = click;

start();
animate();
<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <canvas id="c" width="600" height="400"></canvas>
</body>
</html>
joeblog
  • 1,101
  • 11
  • 17
  • try to minus ball radius from! ball_pos[0] = evt.clientX - 15; ball_pos[1] = evt.clientY - 15; – kpblc Dec 12 '14 at 09:25
  • From a similar post pointed out, I've got a solution that goes like this: function click(evt) { ball_pos[0] = evt.clientX - canvas.offsetLeft; ball_pos[1] = evt.clientY - canvas.offsetTop; } – joeblog Dec 12 '14 at 09:37

0 Answers0