How to simulate click on canvas with coordinates?

Member

by lew , in category: Javascript , 3 months ago

How to simulate click on canvas with coordinates?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 3 months ago

@lew 

To simulate a click on a canvas with coordinates using JavaScript, you can follow these steps:

  1. Get the canvas element using its id or class name:
1
const canvas = document.getElementById('canvasId');


  1. Calculate the coordinates where you want to simulate the click:
1
2
const x = 100; // x-coordinate
const y = 200; // y-coordinate


  1. Create a new MouseEvent object with the appropriate parameters:
1
2
3
4
5
6
const event = new MouseEvent('click', {
  bubbles: true,
  cancelable: true,
  clientX: x,
  clientY: y
});


  1. Dispatch the MouseEvent on the canvas element:
1
canvas.dispatchEvent(event);


By following these steps, you can simulate a click on a canvas with specific coordinates using JavaScript.