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)thenbackground(255)), which erased all drawn lines. Now we only set the background once insetup()so your drawings persist. - Cleaner Cursor Circle:
- Renamed the weight variable to
strokeWeightValto avoid clashing with Processing's built-instrokeWeight()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.
- Renamed the weight variable to
- Smoother Key Handling: Switched to
keyReleased()instead of checkingkeyPressedindraw()—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
相关产品推荐
相关产品推荐

