Skip to content

Instantly share code, notes, and snippets.

@macklinu
Last active December 11, 2015 09:28
Show Gist options
  • Save macklinu/4580025 to your computer and use it in GitHub Desktop.
Save macklinu/4580025 to your computer and use it in GitHub Desktop.
Mouse Events and Cursor

A Processing.js sketch that highlights multiple things:

  • How to use a mostly transparent circle as a cursor
  • Detecting mouse events, such as hovering over a circle and taking action upon mouse clicks
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>No Cursor</title>
<script src="http://cloud.github.com/downloads/processing-js/processing-js/processing-1.4.1.min.js"></script>
<style>
#sketch {
text-align: center;
}
</style>
</head>
<body>
<div id="sketch"><canvas data-processing-sources="noCursor.pde"></canvas></div>
</body>
</html>
int circleX, circleY;
int circleSize = 200;
float mouseHoverDist;
int numClicks = 0;
PFont f;
void setup() {
size(window.innerWidth, window.innerHeight);
smooth();
// turn off the cursor
noCursor();
// set circle to center of the screen
circleX = width/2;
circleY = height/2;
f = createFont("sans-serif", 32);
textFont(f, 18);
}
void draw() {
background(150);
// calculates the distance between mouse location and circle position
mouseHoverDist = dist(mouseX, mouseY, circleX, circleY);
// if the distance is within the circle
fill(mouseHoverDist < circleSize/2 ? color(255, 0, 0, 100) : color(0, 255, 0, 100));
ellipse(circleX, circleY, circleSize, circleSize);
fill(255);
text("Number of clicks: " + numClicks, 10, height-20);
// always run at the end of the loop so it's visible over any other elements
drawCursor();
}
void drawCursor() {
noStroke();
// if you use other ellipseModes, this will ensure
// the center point of the circle is where your mouse is
ellipseMode(CENTER);
// mostly transparent circle (alpha value = 50)
fill(255, 50);
// circle moves with you mouse X and Y
ellipse(mouseX, mouseY, 20, 20);
}
// where one click mouse events happen
void mousePressed() {
// if the mouse is over the circle and you've clicked the mouse
// print that you've clicked the circle and increment the number of clicks recorded
if (mouseHoverDist < circleSize/2) numClicks++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment