Roberto Arias
Roberto Arias

Reputation: 133

Is there a way of clicking an specific point/element in a canvas (with javascript, jquery or selenium)

How can I apply a click at a specific position in a canvas? (using coordinates seems the most logical to me, but can't find any way to do it, any other idea is welcomed). Note that I do not have access to the code that creates the canvas.

EDIT: Some clarification, the canvas has multiple elements being drawn that i can't select with jquery but need to click them. I could find their coordinates manually and do some calculations, but every time i try to pass a click or mouse event into that position is not being taken as a real mouse click (the button that should be clicked, is not).

Upvotes: 4

Views: 1705

Answers (1)

Micha
Micha

Reputation: 563

How about trying

canvas.on('click', function(e) {

    // calculate x y coordinates on canvas
    var x = e.pageX - $(this).offset().left,
    y = e.pageY - $(this).offset().top;

    // implement collision detection via the coordinates the element you want to click (assuming you know where it is)
    if (y > <elementY> && y < <elementY> + <elementHeight>
        && x > <elementX> && x < <elementX> + <elementWidth>) {
        alert('found it');
    }
});

I have no time testing that snippet. If you know the x and y coordinates of your elements within your canvas, that code might just do the trick.

What I tried to do with that snippet is to simulate a bounding box via elmentY and elementY + elementHeight as well as elementX and elementX + elementWidth. If you know all those values, you can simply check whether the x and y values of your click event fall in that said box.

Edit

If you want to trigger a click event at a certain position, define the clickEvent beforehand and set the pageX and pageY attributes.

var e = new jQuery.Event("click");
e.pageX = 10;
e.pageY = 10;
$(<canvas>).trigger(e);

You might have to include the offset of your canvas in the calculations as well.

Upvotes: 1

Related Questions