Add click interaction to HTML Canvas using JavaScript events

Share this video with your friends

Send Tweet

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.

Ray
Ray
~ 7 years ago

// 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);

Stephen James
Stephen James
~ 7 years ago

Why does Y have .125 but X is an integer.

Pascal Chouinard
Pascal Chouinard
~ 7 years ago

Yes, I was wondering as well why does the Y value contains fraction digits if we are only subtracting integer values for the coords?

Ray
Ray
~ 7 years ago

@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.

Ray
Ray
~ 7 years ago

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> -->
Ray
Ray
~ 7 years ago

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.

Pascal Chouinard
Pascal Chouinard
~ 7 years ago

aaah ok, thanks @Ray