ABC
ABC

Reputation: 591

Click on HTML5 canvas

I want to simulate clicks on a canvas with javascript\jQuery for testing reasons, but I didn't find a solution. Here's my code:

var e = new jQuery.Event("click");
            e.pageX = X[index];
            e.pageY = Y[index];
            $("#gamecanvas").trigger(e);

Is it possible to do that ?

For example this game (I searched randomly on the web) How can I click from JS\jQuery ?

Upvotes: 3

Views: 3011

Answers (4)

Barr J
Barr J

Reputation: 10927

This is because, pageX and pageY doesn't get the coordinates of the canvas, I had the same issue my self when trying to create a signature pad.

use this instead:

var e = new jQuery.Event("click");
           //for IE, safari, opera, chrome
           if(e.offsetX != null) {
            e.offsetX= X[index];
            e.offsetY= Y[index];
          }
          //for firefox
              if(e.layerX!= null) {
            e.layerX= X[index];
            e.layery= Y[index];
          }
            $("#gamecanvas").trigger(e);

Upvotes: 0

Bourbia Brahim
Bourbia Brahim

Reputation: 14712

It depends on the event's used on the canvas , whether it's a click , mousedown , .... etc

In the example you just mentioned , the lucn event uses two event :

One (mousemove) for calculating coordinate to get clientX and clientY

Second (mousedown) for lunching ball using last calculated coordinate

So your code should be like :

var mousemove = new jQuery.Event("mousemove");
mousemove.clientX = x;//passed valuue
mousemove.clientY =y;//passed valuue

var mousedown = new jQuery.Event("mousedown");

$("#canvas").trigger(mousemove);
$("#canvas").trigger(mousedown);

Here a pluncker where I created a script to luanch a ball with passed input coordinate or jus throw the ball in the basket directly :)

See here livePlunker

See url code plunker

Hope this will help :

Upvotes: 2

Sridhar Rajan
Sridhar Rajan

Reputation: 105

This example may help you

$('#canvas_element').on("mousedown mouseup", function(e) {
    $('#output').text($('#output').text() + (e.type + " event fired at coords: " + e.pageX + ", " + e.pageY));
});

    x_coord = 1;
    y_coord = 1;

    var e = jQuery.Event( "mousedown", { pageX: x_coord, pageY: y_coord } );
    $('#canvas_element').trigger(e);

    // execute more code

    var e = jQuery.Event( "mouseup", { pageX: 255, pageY: 255 } );
    $('#canvas_element').trigger(e);

working link

Upvotes: 1

Dasma
Dasma

Reputation: 1263

Without know you use case the documentation for jQuery tells me yes: http://api.jquery.com/trigger/

Why you don't search by your self through the very well documented API for jquery?

Upvotes: -1

Related Questions