Skip to content

Commit 7053607

Browse files
committed
First draft
1 parent 841a55b commit 7053607

1 file changed

Lines changed: 29 additions & 16 deletions

File tree

examples/curated/21_Constrain.js

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,50 @@
11
/*
22
* @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 mouse 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.
68
*/
7-
let mx = 1;
8-
let my = 1;
9-
let easing = 0.05;
9+
10+
// Circle's radius
1011
let radius = 24;
12+
13+
// Distance between edge of rectangle and edge of canvas
1114
let edge = 100;
15+
16+
// Distance between center of circle and edge of canvas
17+
// when circle is at edge of rectangle
1218
let inner = edge + radius;
1319

1420
function setup() {
1521
createCanvas(720, 400);
1622
noStroke();
23+
24+
// Use radius mode to pass in radius as 3rd parameter for circle()
1725
ellipseMode(RADIUS);
26+
27+
// Use corners mode to pass in rectangle corner coordinates
1828
rectMode(CORNERS);
29+
30+
describe(
31+
"Pink rectangle on a grey background. " +
32+
"A user uses their mouse to move a white circle within the pink rectangle."
33+
);
1934
}
2035

2136
function draw() {
2237
background(230);
2338

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);
39+
// Draw rectangle
3340
fill(237, 34, 93);
3441
rect(edge, edge, width - edge, height - edge);
42+
43+
// Calculate circle coordinates constrained to rectangle
44+
let circleX = constrain(mouseX, inner, width - inner);
45+
let circleY = constrain(mouseY, inner, height - inner);
46+
47+
// Draw circle
3548
fill(255);
36-
ellipse(mx, my, radius, radius);
49+
circle(circleX, circleY, radius);
3750
}

0 commit comments

Comments
 (0)