Skip to content

Commit 028bfc0

Browse files
authored
Merge pull request #6 from processing/Constrain
Constrain
2 parents 800355d + 581325b commit 028bfc0

2 files changed

Lines changed: 29 additions & 17 deletions

File tree

examples/curated/21_Constrain.js

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,49 @@
1-
/*
1+
/**
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 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.
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. The cursor moves a white circle within the pink rectangle.'
32+
);
1933
}
2034

2135
function draw() {
2236
background(230);
2337

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
3339
fill(237, 34, 93);
3440
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
3547
fill(255);
36-
ellipse(mx, my, radius, radius);
48+
circle(circleX, circleY, radius);
3749
}

examples/curated/21_Constrain.png

8.44 KB
Loading

0 commit comments

Comments
 (0)