You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

p5.js如何检测鼠标是否点击了画布内的指定图形元素?

实现思路

你可以将目标元素的位置、尺寸参数抽为可复用的全局变量,搭配通用的几何碰撞检测函数实现精准点击判定,不需要硬编码坐标边界,后续调整目标元素属性时判定逻辑也会自动同步。

完整修改后的sketch.js代码

let Coins = 0;
// 目标圆形参数,绘制和碰撞检测共用,修改只需调整这里的数值
const targetCircle = {
  x: 200,
  y: 200,
  diameter: 50
}

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

function draw() {
  background(100)
  // 直接用公共参数绘制圆形,无需硬写数值
  circle(targetCircle.x, targetCircle.y, targetCircle.diameter)
  text(Coins, targetCircle.x - (textWidth(Coins) / 2), 150)
}

// 通用圆形点击检测函数:判断点(px,py)是否在圆心(cx,cy)、直径d的圆内
function isPointInCircle(px, py, cx, cy, d) {
  // 计算点击位置到圆心的距离的平方,和半径平方比较(不开根号性能更优,判定效果一致)
  const distSq = (px - cx) ** 2 + (py - cy) ** 2;
  return distSq <= (d / 2) ** 2;
}

function mouseClicked() {
  // 仅当点击命中目标圆形时才增加硬币
  if (isPointInCircle(mouseX, mouseY, targetCircle.x, targetCircle.y, targetCircle.diameter)) {
    Coins += 1;
  }
}

其他形状的适配方案

如果后续要换成矩形等其他形状,只需替换对应的检测函数即可,不需要改整体逻辑:

  • 矩形点击检测函数示例:
// rx/ry为矩形左上角坐标,rw/rh为矩形宽高
function isPointInRect(px, py, rx, ry, rw, rh) {
  return px >= rx && px <= rx + rw && py >= ry && py <= ry + rh;
}

所有目标元素的参数都和绘制逻辑共用,不存在硬编码的坐标判断,修改元素位置尺寸只需要调整变量初始值即可。


内容的提问来源于stack exchange,提问作者KitchenSpice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 09:36:04