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

如何在p5.js中实现圆形按钮及点击状态切换功能?

Detecting Circular Button Clicks in p5.js (Toggle Bit States)

Got it, let's break down how to solve your problem of detecting clicks on those circular buttons and toggling their states. The key part is checking if the mouse click falls within the bounds of each circle, which we can do using p5.js's built-in dist() function.

Here's the complete working code with explanations:

var array = [0,1,0,1,1,1,1,1];
var values = [128,64,32,16,8,4,2,1];
var positionsX = [50,100,150,200,250,300,350,400]; // Store each circle's x-center
var d = 20; // Diameter of the circles
var r = d/2; // Radius (for precise click detection)

function setup(){
  createCanvas(600,600);
  textStyle(BOLDITALIC);
  textSize(50);
}

function draw(){
  background(51);
  let currentTotal = calculate(array);
  
  // Display the calculated total
  fill(255);
  text(currentTotal, 250, 500);
  
  let crclX = 50;
  // Draw each circle based on its state
  for (let i = 0; i < 8; i++){
    fill(array[i] === 1 ? color(0,255,0) : color(255,0,0));
    circle(crclX, 50, d);
    crclX += 50;
  }
}

// Calculate the sum of values where the bit is 1
function calculate(array){
  let total = 0;
  for (let i = 0; i < 8; i++){
    if (array[i] === 1){
      total += values[i];
    }
  }
  return total;
}

// Handle mouse clicks to toggle circle states
function mouseClicked(){
  for (let i = 0; i < 8; i++){
    // Check if the click is within the circle's bounds
    // dist(mouseX, mouseY, circleX, circleY) <= radius
    if (dist(mouseX, mouseY, positionsX[i], 50) <= r){
      array[i] = 1 - array[i]; // Toggle state: 0 ↔ 1
    }
  }
}

Key Details:

  • Tracking Circle Positions: The positionsX array stores the x-coordinate of each circle's center, making it easy to reference each button's location during click checks.
  • Click Detection Logic: In mouseClicked(), we loop through each circle and use dist() to measure the distance between the click point and the circle's center. If this distance is ≤ the circle's radius (r), the click is inside the button.
  • State Toggle: array[i] = 1 - array[i] is a clean way to flip the state—turning 0 to 1 and 1 to 0 without extra conditionals.
  • Visual Feedback: The draw() function uses green for active (1) states and red for inactive (0) states, updating the displayed total each frame based on the current bit states.

Quick Note:

In your initial final code, you used dist(...) <= d (diameter) instead of the radius. This makes the clickable area twice as large as the visible circle. Using the radius ensures clicks only register when the user taps directly on the circle itself.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:17:42