p5.js:在 html 元素之上渲染 canvas 而不阻塞鼠标交互

p5.js: Render canvas on top of html-elements without blocking mouse interactions

我正在尝试呈现一个带有 p5.js 的省略号,它跟随鼠标并在鼠标与页面上的元素交互时发生变化。

我有一个简单的设置,其中我使用 CSS 隐藏常规光标,并在每次 canvas 刷新时在 mouse-X 和 -Y 处画一个圆圈。一切都按预期工作,但 canvas 位于页面元素后面,所以我的 "new cursor" 将出现在所有按钮、链接等后面。我尝试通过给按钮一个 z-index 来解决这个问题-1 并将 canvas' pointer-events 设置为 none,但 mouseentermouseleave 未注册到位于 [= 后面的按钮41=] 现在(我的假设是 pointer-events: none; 将使鼠标 "ignore" 成为 canvas 并因此将鼠标悬停在按钮上)。

我该如何解决这个问题?

这是我的问题的最小设置:

let x = 100,
  y = 100,
  angle1 = 0.0,
  segLength = 50;

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

function draw() {
  clear();
  x = mouseX;
  y = mouseY;
  let c; 
  //
  if (document.getElementById("defaultCanvas0").classList.contains("hover")) {
    c = color(255, 0, 0);
    ellipse(x, y, 30, 30).fill(c);
  } else {
   c = color(0, 255, 0);
    ellipse(x, y, 20, 20).fill(c);
  }
  //
  
}

const button = document.getElementById("testButton"),
  test = document.getElementById("defaultCanvas0");

//
// Listen for hover
button.addEventListener("mouseenter", function(e) {
  document.getElementById("defaultCanvas0").classList.add("hover")
})
button.addEventListener("mouseleave", function(e) {
  document.getElementById("defaultCanvas0").classList.remove("hover")
})
body, * {
  cursor: none;
}

#testButton {
  position: absolute;
  top: 100px;
  left: 100px;
  z-index: 0;
}

canvas {
  pointer-events: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
<div>
  <button id="testButton">
    button
  </button>
</div>

按照你的想法

giving the button a z-index of -1 and setting the canvas' pointer-events to none,

您只需将 canvas' position 设置为 absolute 即可使其正常工作,请参阅下面的代码段。我想如果位置不是绝对的,canvas 不知道指针事件 "pass on" 的位置。

let x = 100,
  y = 100,
  angle1 = 0.0,
  segLength = 50;

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

function draw() {
  clear();
  x = mouseX;
  y = mouseY;
  let c; 
  //
  if (document.getElementById("defaultCanvas0").classList.contains("hover")) {
    c = color(255, 0, 0);
    ellipse(x, y, 30, 30).fill(c);
  } else {
   c = color(0, 255, 0);
    ellipse(x, y, 20, 20).fill(c);
  }
  //
  
}

const button = document.getElementById("testButton"),
  test = document.getElementById("defaultCanvas0");

//
// Listen for hover
button.addEventListener("mouseenter", function(e) {
  document.getElementById("defaultCanvas0").classList.add("hover")
})
button.addEventListener("mouseleave", function(e) {
  document.getElementById("defaultCanvas0").classList.remove("hover")
})
body, * {
  cursor: none;
}

#testButton {
  position: absolute;
  top: 100px;
  left: 100px;
  z-index: -1;
}

canvas {
  position: absolute;
  pointer-events: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
<div>
  <button id="testButton">
    button
  </button>
</div>