An Introduction To Programming With Processing

Constraining Values

The constrain() function works by clamping a value between a range that you specify. It accepts three parameters, the first parameter is the value that you want to constrain and in our case this would be the variable yPos. The next parameter is the minimum value of the range you would like the value constrained between and the final parameter is the maximum value for the range that the value yPos will be constrained between. Modify the image() statement to match the following code fragment, and complete your sketch:
image(doors,0, constrain(yPos, height- doors.height, 0));
At first this statement could look a little intimidating, but in fact you already know what's going on in most of the statement and it's only the Y parameter of the image() function that is somewhat different. As you are aware the image() function accepts three parameters, firstly the object variable containing the image (i.e. doors), secondly the value of the X position you would like the image rendered at and finally the image's Y position. This statement is in the draw() structure and as a result will be repeated throughout the program's run-cycle, this means that every time the user moves the mouse the difY variable will change and as a result so too will the yPos variable. It is therefore necessary for this statement to be within the draw() structure, or these changes will never be seen. The Y parameter of the image() function accepts an expression in this example, the expression consisting of the constrain() function:
constrain(yPos, height - doors.height, 0)
Image Constrain 01
Image Constrain 02
This expression when evaluated, returns the value of the image() function's Y parameter. The constrain() function clamps the yPos value so that the image is never raised above the value returned from height – doors.height and never lowered below 0, this will be the point where the image's origin matches the Display Window's origin. The area which the image's motion is constrained to, exists above and outside of what is visible within the Display Window. Of course if you think this example could be easier to read, you're probably right. For example you could declare a global variable to which you assign the previous expression to within the draw() structure. The additional overhead that such an action would create in this example is minimal, for example:
float imageY;

void setup(){
  doors = loadImage("doorsClosed.png");

void draw(){
  imageY = constrain(yPos, height- doors.height, 0);
  image(doors,0, imageY);
However in order to demonstrate how expressions can be used as parameters in code, this example uses the former method which does not accommodate for the imageY variable. Nonetheless if you would like to see how this example can be implemented you can examine the comments in the imageScroll.pde file.

Download the example file