# p5 Dynamic Mode

Let’s make our first interactive sketch

```function setup() {
createCanvas(500, 500);
}

function draw() {
background(255, 255, 255);
line(250, 250, mouseX, mouseY);
}
```

What if we move the background line in the setup function?

```function setup() {
createCanvas(500, 500);
background(255, 255, 255);
}

function draw() {
line(250, 250, mouseX, mouseY);
}
```

Before, the background was filled every frame, which is very fast 60 fps.
With this layering it works like a creative tool.

Change the rectangle with an ellipse (they happen have the same number of parameters)

```function draw() {
line(mouseX, mouseY, pmouseX, pmouseY);
}
```

pmouseX, pmouseY is the last mouse position, they are useful system variables.

Make a circle that follows the mouse!

Try to switch the mouse:

`ellipse(mouseY, mouseX, 50, 50);`

And try this:

```background(255, 255, 255);
ellipse(mouseX, height-mouseY, 50, 50);
```

height and width are constant representing the size of the canvas.
The expression width-mouseY will be resolved before the ellipse gets drawn.

Draw an ellipse that mirrors the mouse position on both axis!

You can draw more than one object on each draw iteration:

```background(255, 255, 255);
ellipse(mouseX, mouseY, 50, 50);
ellipse(width-mouseX, height-mouseY, 50, 50);
```

A less predictable behavior:
```background(255, 255, 255);
ellipse(mouseX, mouseY, 50, 50);
ellipse(width-mouseY, mouseX, 50, 50);```

You can create all sorts of complex relationships starting from the mouse coordinate

```ellipse(mouseX, height-mouseY, 50, 50);
ellipse(mouseX/2, height-mouseY/2, 50, 50);
```

Make a complex set of relationships between 5 or more shapes!
(redraw the background at every refresh)

P5 provides two ways to detect the mouse clicks, as an event and as a state variables:

```
function setup() {
createCanvas(500, 500);
}

function draw() {
background(237, 34, 93);

fill(0);

if (mouseIsPressed)
ellipse(250, 250, 100, 100);
else
rect(250, 250, 100, 100);
}

//this function is called every time you press a mouse button
function mousePressed() {
print("mouse has been clicked");
}

//this function is called every time you release a mouse button
function mouseReleased() {
print("mouse has been released");
}

```

Now we can make a simple drawing application that draw a line only if the mouse is down.

Check the reference for more mouse related functions
mouseMoved()
mouseDragged()
mousePressed()
mouseReleased()
mouseClicked()
mouseWheel()

Posted in