Processing原生与在线Sketch渲染结果不一致问题咨询
Let's break down the issues causing the inconsistent behavior between native Processing and Processing.js, then fix them:
Key Issues
1. Incorrect Initialization of x and y
Your global variables x and y are initialized before the setup() function runs. At this point, Processing hasn't set the canvas dimensions from size(1100, 500) yet—so width and height use their default values (100 in native Processing, possibly 0 in Processing.js). This means x and y don't get the values you expect (3*1100/2 and 3*500/2), leading to different starting positions for your triangle across the two environments.
2. Unmanaged Transformation Matrix
You're calling translate(x, y) and rotate(angle) every frame without wrapping them in pushMatrix() and popMatrix(). This causes the transformation to accumulate each frame: every draw() call adds another translation and rotation on top of the previous one. In native Processing, this might not break your logic immediately (or you might not have noticed the drift), but in Processing.js, this cumulative transformation makes the screenY() values behave unpredictably, triggering your ellipse-drawing condition constantly.
Fixed Code
Here's the corrected version of your sketch that works consistently in both native Processing and Processing.js:
/* Program that rotates a triangle and draws an ellipse when the third vertex is on top of the screen*/ float x, y; float previous_1 = 0.0; float previous_2 = 0.0; float current; float angle = 0.0; void setup() { size(1100, 500); // Initialize x and y AFTER setting canvas size x = 3 * width / 2; y = 3 * height / 2; } void draw() { fill(0, 30); // Save the current transformation state pushMatrix(); // Update rotation angle angle -= 0.02; translate(x, y); rotate(angle); // Display triangle triangle(-50, -50, -30, 30, -90, -60); // Detect whether third vertex is at the top (local minimum of screenY) current = screenY(-90, -60); if (previous_1 < previous_2 && previous_1 < current) { fill(128, 9, 9); ellipse(-90, -60, 7, 10); } // Restore original transformation state popMatrix(); // Update previous positions previous_2 = previous_1; previous_1 = current; }
Explanation of Fixes
- Moved
xandyinitialization tosetup(): Now they use the actual canvas dimensions set bysize(), ensuring the triangle starts at the same position in both environments. - Added
pushMatrix()andpopMatrix(): These functions save the original coordinate system before applying transformations, then restore it after drawing the triangle. This prevents cumulative transformation drift, soscreenY()calculates the vertex's position correctly every frame.
With these changes, the ellipse will only draw when the third vertex reaches the top of the screen, consistent across both native Processing and Processing.js.
内容的提问来源于stack exchange,提问作者Alchemille

