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

如何在p5.js中向mousePressed函数传递props参数

问题解决:点击时记录鼠标位置与被点击对象信息

问题根源

  • draw()函数每秒执行约60次,你在其中直接调用mousePressed(i),导致每次循环都会触发日志输出,和鼠标点击动作无关。
  • 错误调用p5.js内置的mousePressed事件函数,该函数由系统在鼠标点击时自动触发,不能主动调用。
  • 变量名错误:代码中使用了未定义的circle,应改为circles。

修正后的代码

let circles = [];

function setup() {
    createCanvas(800, 800);
    for (let i = 0; i < 3; i++) {
        circles.push([random(0, width), random(0, height)])
    };
};

function draw() {
    background(0);
    for (let i = 0; i < circles.length; i++) {
        fill('rgba(50,250,50,1)');
        ellipse(circles[i][0], circles[i][1], 5, 5);
    };
};

function mousePressed() {
    let mx = mouseX;
    let my = mouseY;
    // 遍历所有圆,判断是否点击命中
    for (let i = 0; i < circles.length; i++) {
        let cx = circles[i][0];
        let cy = circles[i][1];
        // 计算鼠标到圆心的距离,和圆半径(2.5,因为直径是5)比较
        let distance = dist(mx, my, cx, cy);
        if (distance <= 2.5) {
            console.log("鼠标位置:", mx, my);
            console.log("被点击的圆坐标:", cx, cy);
        }
    }
}

修改说明

  • 移除draw()中对mousePressed(i)的调用,避免无意义的重复触发日志。
  • 让mousePressed回归内置事件函数的作用,仅在鼠标点击时被系统触发。
  • 增加点击命中判定:使用p5.js的dist()函数计算鼠标与圆心的距离,当距离小于等于圆半径时,判定为点击到该圆,输出对应的位置信息。
  • 修正变量名错误,将circle改为定义好的circles。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:05:45