Saturday, October 11, 2025
HomeLanguagesJavascriptp5.js | Mouse | mouseX

p5.js | Mouse | mouseX

The mouseX variable in p5.js is used to store the current horizontal position of the mouse, relative to (0, 0) of the canvas. If touch is used instead of mouse input, mouseX will hold the x value of the most recent touch point.

Syntax:

mouseX

Below programs illustrate the mouseX variable in p5.js:

Example 1: This example uses mouseX variable to display position.




function setup() {
      
    // Create canvas
    createCanvas(1000, 400);
      
    // Set the text size
    textSize(20); 
}
   
function draw() {
      
    // Set background color
    background(200);
      
    // Create rectangle
    rect(mouseX, height/2, 30, 30);
      
    // Display position
    text("Position of mouse relative to canvas is "
            + mouseX, 30, 40);
}


Output:

Example 2: This example uses mouseX variable to display position.




function setup() {
  
    // Create canvas
    createCanvas(1000, 400);
      
    // Set font size
    textSize(20);
}
   
function draw() {
      
    // Set background color
    background(200);
      
    // Create circle
    circle(mouseX, mouseY, 30);
      
    // Display position
    text("Position of mouseX relative to canvas: "
            + mouseX, 30, 40);
}


Output:

Reference: https://p5js.org/reference/#/p5/mouseX

RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6719 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6839 POSTS0 COMMENTS
Ted Musemwa
7101 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS