Reputation: 3063
I'm really new to both the canvas and javascript. I was trying to make a button that did something when you click it. When I created a click event for a button, I couldn't figure out why it wasn't working. Then, when I tried troubleshooting I discovered that the x,y coords of the rectangle shape was completely off compared to where the click event said I was clicking. I'm completely baffled. I added some code just to make sure I wasn't insane. The clicks are saying my coords begin a lot higher on the X axis despite being on the far left of the canvas.
The shape is at X = 565 The click says I'm at X = 1161
Here's my code:
function bigButton(x, y, strTxt)
{
var getID = document.getElementById("canvas_1");
if (getID.getContext)
{
var btnCtx = getID.getContext("2d");
btnCtx.font = "Italic 32pt Times";
btnCtx.textAlign = "center";
btnCtx.textBaseline = "middle";
var btnW = 150;
var btnH = 50;
var cx = x - btnW/2;
var cy = y - btnH/2;
var left = cx;
var right = cx + btnW;
var top = cy;
var bottom = cy + btnH;
btnCtx.strokeRect(cx, cy, btnW, btnH);
btnCtx.fillText(strTxt, x, y);
btnCtx.font = "24pt Helvetica";
btnCtx.fillText("Coordinates of Rectangle: X = " + cx + " Y = " + cy, cx, cy + 90);
getID.addEventListener("click", function(event)
{
var clickX = event.x;
var clickY = event.y;
alert(clickX + " " + clickY);
}, false);
}
}
Upvotes: 1
Views: 56
Reputation:
The client coordinates in the event are relative to client window. The x
and y
properties that you are currently using is not part of a standard event so they should be avoided in any case. Use clientX/Y
or one of the others instead.
In order to make them relative to canvas you can simply subtract the canvas' absolute position.
Here is one way of doing it:
getID.addEventListener("click", function(event) {
var rect = getID.getBoundingClientRect(); // get abs. region of canvas
var clickX = event.clientX - rect.left; // adjust x
var clickY = event.clientY - rect.top; // adjust y
alert(clickX + " " + clickY);
}, false);
Also make sure you don't set the canvas size using CSS but it's width
and height
attributes (or properties if done in JS) as the bitmap will be scaled to the element size which also affects the mouse position (relative to the bitmap).
If you apply padding or border to the canvas they will affect the relative position as well. Do either:
display: block;
Upvotes: 2