robot | get screen size | mouse click | Search

The moveMouse function moves the mouse cursor to a specified position on the primary monitor by scaling the input coordinates and using the mouse-controller library. It requires the node-screenshots library to get the list of monitors.

Run example

npm run import -- "move mouse"

move mouse

const { Monitor } = require("node-screenshots")
const MouseController = require('mouse-controller')
const mc = new MouseController();

function moveMouse(x, y) {
  let monitors = Monitor.all()
  monitors.sort((a, b) => (a.x + a.y) - (b.x + b.y))
  /*console.log({
    x: monitors[0].x,
    y: monitors[0].y,
    width: monitors[0].width,
    height: monitors[0].height,
  })*/
  mc.move(x * monitors[0].width * 3 + monitors[0].x, y * monitors[0].height)
}

module.exports = moveMouse

What the code could have been:

const { Monitor } = require("node-screenshots");
const MouseController = require('mouse-controller');

/**
 * Move the mouse cursor to the specified coordinates.
 * 
 * @param {number} x - The x-coordinate to move to (0 to 1).
 * @param {number} y - The y-coordinate to move to (0 to 1).
 */
function moveMouse(x, y) {
  // Get all available monitors
  const monitors = Monitor.all();

  // Sort monitors by their center x-coordinate
  monitors.sort((a, b) => (a.x + a.width / 2) - (b.x + b.width / 2));

  // Get the primary monitor
  const primaryMonitor = monitors[0];

  // Move the mouse to the specified coordinates on the primary monitor
  const mouse = new MouseController();
  mouse.move(x * primaryMonitor.width, y * primaryMonitor.height);
}

module.exports = moveMouse;

Function Breakdown: moveMouse

Overview

The moveMouse function moves the mouse cursor to a specified position on the primary monitor.

Requirements

Parameters

Functionality

  1. Retrieves a list of monitors using the Monitor.all() method from the node-screenshots library.
  2. Sorts the list of monitors by their x + y coordinates in ascending order.
  3. Calculates the x and y coordinates of the position to move the mouse to by scaling the input coordinates by the width and height of the primary monitor, respectively.
  4. Moves the mouse cursor to the calculated position using the mouse-controller library.

Export

The moveMouse function is exported as a module.