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

P5.js手机端如何使用mousePressedOver并实现多点触控功能?

P5.js 多点触控实现方案

p5.js 原生支持多点触控,核心通过内置的touches数组实现,该数组会实时存储所有当前活跃触控点的坐标信息,每个元素包含x、y属性对应触控点在画布上的位置。
你可以按照以下步骤修改代码适配多点触控:

  • 替换单点判断逻辑:放弃仅判断mouseIsPressed的单点逻辑,改为遍历touches数组校验所有触控点
  • 阻止移动端默认行为:新增事件回调返回false,避免操作时触发页面缩放、滑动回弹等默认交互
  • 精灵触控检测:用p5.play内置的collidePoint方法,判断触控点是否落在精灵范围内

修改后的完整代码

var laugh, laughI, sadI, sad, titleI, title, annoyI, annoy, motiI, moti
var stressI, stress, angryI, angry;

function preload(){
    laughI  = loadImage("images/laugh.png");
    sadI    = loadImage("images/sad.png");
    titleI  = loadImage("images/title.png");
    annoyI  = loadImage("images/annoy.png");
    motiI   = loadImage("images/motivation.png");
    stressI = loadImage("images/stress.png");
    angryI  = loadImage("images/angry.png");
}

function setup() {
    createCanvas(windowWidth, 1800);
    // 阻止移动端触控默认行为
    document.addEventListener('touchstart', e => e.preventDefault(), {passive: false});

    title = createSprite(windowWidth/2, 80)
    title.addImage(titleI)
    title.scale = 0.9;

    laugh = createSprite(windowWidth/2, 270);
    laugh.addImage(laughI);
    laugh.scale = 0.2;

    sad = createSprite(windowWidth/2, 550);
    sad.addImage(sadI);
    sad.scale = 0.2;

    annoy = createSprite(windowWidth/2, 830);
    annoy.addImage(annoyI);
    annoy.scale = 0.2;

    moti = createSprite(windowWidth/2, 1110);
    moti.addImage(motiI);
    moti.scale = 0.2;

    stress = createSprite(windowWidth/2, 1390);
    stress.addImage(stressI);
    stress.scale = 0.2;

    angry = createSprite(windowWidth/2, 1670);
    angry.addImage(angryI);
    angry.scale = 0.2;
}

function draw() {
    background(0);
    // 重置所有精灵可见状态,如果不需要抬起恢复可以删掉这部分
    laugh.visible = sad.visible = annoy.visible = moti.visible = stress.visible = angry.visible = true;
    // 遍历所有触控点,检测是否命中对应精灵
    for(let i=0; i<touches.length; i++){
        let touchX = touches[i].x;
        let touchY = touches[i].y;
        if(laugh.collidePoint(touchX, touchY)) laugh.visible = false;
        if(sad.collidePoint(touchX, touchY)) sad.visible = false;
        if(annoy.collidePoint(touchX, touchY)) annoy.visible = false;
        if(moti.collidePoint(touchX, touchY)) moti.visible = false;
        if(stress.collidePoint(touchX, touchY)) stress.visible = false;
        if(angry.collidePoint(touchX, touchY)) angry.visible = false;
    }
   drawSprites();
}

如果不需要触控抬起后恢复精灵显示,删掉draw函数开头重置visible状态的代码即可,触控过的精灵会一直保持隐藏状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:06:03