Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 530
ABC Avatar asked Nov 28 '25 12:11

ABC


2 Answers

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 :

like image 67
Spring Avatar answered Nov 30 '25 00:11

Spring


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

like image 29
Sridhar Rajan Avatar answered Nov 30 '25 01:11

Sridhar Rajan