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

Processing技术问询:实现光标跟随圆形及可调节线条粗细的绘图程序

Fixing Your Processing Drawing Sketch with Cursor Tracking

Hey there! Let's get your sketch working exactly how you want it—tracking the cursor with a circle, drawing persistent lines, and adjusting stroke weight smoothly. Here's the complete polished code plus breakdowns of the key fixes:

Complete Working Code

float strokeWeightVal = 2; // Renamed to avoid conflicting with Processing's built-in strokeWeight() function

void setup() {
  size(640, 360);
  noSmooth();
  background(255); // Set initial white background once here
  strokeWeight(strokeWeightVal);
}

void draw() {
  // Draw cursor-following circle (behind lines by default)
  fill(126);
  noStroke(); // Remove outline for cleaner cursor
  ellipse(mouseX, mouseY, strokeWeightVal, strokeWeightVal); // Match circle size to stroke weight

  // Draw lines when mouse is pressed
  if (mousePressed) {
    stroke(0);
    line(mouseX, mouseY, pmouseX, pmouseY);
  }
}

// Handle stroke weight adjustments with key releases (avoids rapid repeated changes)
void keyReleased() {
  if (key == '+' || key == '=') { // Include '=' for keyboards without dedicated '+'
    strokeWeightVal += 0.5;
    strokeWeight(strokeWeightVal);
  }
  if (key == '-' || key == '_') { // Include '_' as fallback
    strokeWeightVal = max(0.5, strokeWeightVal - 0.5); // Prevent weight from getting too small
    strokeWeight(strokeWeightVal);
  }
}

Key Improvements & Explanations

  • Fixed Background Overwrite: Your original draw() function cleared the screen twice (background(0) then background(255)), which erased all drawn lines. Now we only set the background once in setup() so your drawings persist.
  • Cleaner Cursor Circle:
    • Renamed the weight variable to strokeWeightVal to avoid clashing with Processing's built-in strokeWeight() method (this eliminates unexpected bugs).
    • Made the circle size match the current stroke weight, so it visually previews how thick your next lines will be.
    • Added noStroke() to remove the circle's outline for a cleaner cursor look.
  • Smoother Key Handling: Switched to keyReleased() instead of checking keyPressed in draw()—this means each key press adjusts the weight only once, instead of spamming changes while holding the key. We also included fallback keys for better keyboard compatibility.
  • Stroke Weight Boundary: Used max(0.5, ...) to ensure the stroke weight never drops below a visible minimum (0.5).

Quick Extra Tips

  • If you want the cursor circle to appear on top of drawn lines, move the ellipse code to the end of the draw() function.
  • Add a canvas reset feature by adding this to the keyReleased() function:
    if (key == 'r') {
      background(255);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:51:49