Being able to draw shapes is cool and all, but we want to add interactivity to our graphics!
In this lesson, we will learn how to add 'click'
handlers to our canvas
elements using the addEventListener
method.
// if you want top right to be: positive, positive, and. . .
// you want bottom left to be: negative, negative. . .
const x = (event.clientX - container.left) - container.width/2;
const y = container.height/2 - (event.clientY - container.top);
Why does Y have .125 but X is an integer.
Yes, I was wondering as well why does the Y value contains fraction digits if we are only subtracting integer values for the coords?
@Stephen James & @Pascal Chouinard: I suspect, in this case, canvas.getBoundingClientRect() top and bottom are not integers. That is, while the Bounding Client Rect reports alignment to integers on the x axis, it does not report alignment to integers on the y axis.
Likely if you remove the <H1> above the canvas, you would see integer alignment from the events.
<!-- <h1>Add click interaction to HTML Canvas</h1> -->The replies above included the notion of removing the H1 line to see integer alignment of the canvas. But the back-end filtered it out.
Sorry, I can't get edit to work in this thread.
aaah ok, thanks @Ray