processing / p5.js

p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
http://p5js.org/
GNU Lesser General Public License v2.1
21.45k stars 3.29k forks source link

Prevent mouseIsPressed if not directly over canvas element #7196

Closed Tsourdox closed 3 days ago

Tsourdox commented 2 weeks ago

Topic

Is there a way to prevent the mouseIsPressed to become true if there is an element overlaying the canvas?

Basically I don't want to draw the circle when the mouse is over the div element.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.10.0/p5.min.js"></script>

  <style>
    #overlay {
      position: fixed;
      top: 50px;
      left: 50px;
      width: 5rem;
      height: 5rem;
      background: red;
      opacity: .4;
    }
  </style>
</head>

<body>
  <div id="overlay"></div>

  <script>
    overlay.onclick = (e) => {
      e.stopPropagation();
      return false;
    };
    overlay.onmouseover = (e) => {
      e.stopPropagation();
      return false;
    };

    function setup() {
      createCanvas(400, 400);
    }

    function draw() {
      background(220);
      fill("black");
      if (mouseIsPressed) {
        circle(mouseX, mouseY, 20);
      }
    }
  </script>
</body>

</html>
welcome[bot] commented 2 weeks ago

Welcome! 👋 Thanks for opening your first issue here! And to ensure the community is able to respond to your issue, please make sure to fill out the inputs in the issue forms. Thank you!

sikaili commented 1 week ago

Hi @Tsourdox,

mouseIsPressed is a boolean that indicates whether the mouse is pressed (true if pressed, false otherwise). It’s not an event like mousePressed(), and it’s independent of the mouse position.

I made a working example for your use case, which stops drawing the circle when hovering over an overlay: Example

let isMouseInOverlay = false;
const overlayElement = document.querySelector('#overlay');

overlayElement.addEventListener('mouseover', () => {
  isMouseInOverlay = true;
});

overlayElement.addEventListener('mouseout', () => {
  isMouseInOverlay = false;
});

function setup() { 
  createCanvas(400, 400);
}

function draw() { 
  background(255, 100, 100);
  if (mouseIsPressed && !isMouseInOverlay) {
    ellipse(mouseX, mouseY, 100);
  }
}

Additionally, here’s another example comparing mousePressed() and mouseIsPressed: Comparison example

Hope this helps!

limzykenneth commented 3 days ago

Thanks @sikaili for answering here! @Tsourdox if you have further questions or need additional help with your code, feel free to join the community Discord if you haven't already.