|
1 | | -/* |
| 1 | +/** |
2 | 2 | * @name Constrain |
3 | | - * @arialabel Pink rectangle on a grey background. A user uses their mouse to move a white circle within the pink rectangle |
4 | | - * @description Move the mouse across the screen to move |
5 | | - * the circle. The program constrains the circle to its box. |
| 3 | + * @description This example draws a circle as the cursor's position but |
| 4 | + * keeps the circle within a rectangle. It does so by passing the |
| 5 | + * mouse's coordinates into the |
| 6 | + * <a href="https://p5js.org/reference/#/p5/constrain" target="_blank">constrain()</a> |
| 7 | + * function. |
6 | 8 | */ |
7 | | -let mx = 1; |
8 | | -let my = 1; |
9 | | -let easing = 0.05; |
| 9 | + |
| 10 | +// Circle's radius |
10 | 11 | let radius = 24; |
| 12 | + |
| 13 | +// Distance between edge of rectangle and edge of canvas |
11 | 14 | let edge = 100; |
| 15 | + |
| 16 | +// Distance between center of circle and edge of canvas |
| 17 | +// when circle is at edge of rectangle |
12 | 18 | let inner = edge + radius; |
13 | 19 |
|
14 | 20 | function setup() { |
15 | 21 | createCanvas(720, 400); |
16 | 22 | noStroke(); |
| 23 | + |
| 24 | + // Use radius mode to pass in radius as 3rd parameter for circle() |
17 | 25 | ellipseMode(RADIUS); |
| 26 | + |
| 27 | + // Use corners mode to pass in rectangle corner coordinates |
18 | 28 | rectMode(CORNERS); |
| 29 | + |
| 30 | + describe( |
| 31 | + 'Pink rectangle on a grey background. The cursor moves a white circle within the pink rectangle.' |
| 32 | + ); |
19 | 33 | } |
20 | 34 |
|
21 | 35 | function draw() { |
22 | 36 | background(230); |
23 | 37 |
|
24 | | - if (abs(mouseX - mx) > 0.1) { |
25 | | - mx = mx + (mouseX - mx) * easing; |
26 | | - } |
27 | | - if (abs(mouseY - my) > 0.1) { |
28 | | - my = my + (mouseY - my) * easing; |
29 | | - } |
30 | | - |
31 | | - mx = constrain(mx, inner, width - inner); |
32 | | - my = constrain(my, inner, height - inner); |
| 38 | + // Draw rectangle |
33 | 39 | fill(237, 34, 93); |
34 | 40 | rect(edge, edge, width - edge, height - edge); |
| 41 | + |
| 42 | + // Calculate circle coordinates constrained to rectangle |
| 43 | + let circleX = constrain(mouseX, inner, width - inner); |
| 44 | + let circleY = constrain(mouseY, inner, height - inner); |
| 45 | + |
| 46 | + // Draw circle |
35 | 47 | fill(255); |
36 | | - ellipse(mx, my, radius, radius); |
| 48 | + circle(circleX, circleY, radius); |
37 | 49 | } |
0 commit comments