mouseX Marks the Spot

Last week we talked about animations that run automatically. Wouldn’t it be cool if your graphic would change depending on where your mouse was on the screen? By using the mouseX and mouseY code you can! This week, we will look at how to use this code alongside our draw function to make some interactive programs.

These two bits of code work just like a variable would. The only difference is that you don’t define a value for them. The computer is constantly tracking your mouse and therefore always has the information needed. You can use them as coordinates, sizes, math components, even as a color value. There is one restriction, they have to be used inside the draw function. This is because the computer needs to know that you want it to constantly update the value of those pieces of code.

MouseX and mouseY are fantastic to use when you want to easily change things up without having to use a ton of math. They will also come in handy when we look at if and if/else statements.

One of my favorite projects is a drawing program that creates circles of different colors dots based on where your mouse is. It has very simple code which is below.

background(201, 201, 201);
var dotSize = 11;
mouseMoved = function() {
fill(mouseX, mouseY, mouseY*mouseX);
stroke(mouseY, 32, mouseX);
ellipse(mouseX, mouseY, dotSize, dotSize);

Leave a Reply

Your email address will not be published. Required fields are marked *