Random Hearts

Random Hearts

February 14, 2017

example processing


This program takes the scaling heart example and modifies that code to draw random hearts all over the screen:

void setup() {
  size(300, 300);

void draw() {

  float heartSize = random(10, 100);
  float heartX = random(width);
  float heartBottomY = random(height+heartSize);

  float r = random(255);

  fill(r, 0, 0);
  stroke(r, 0, 0);

  //fill in line that sometimes appears between halves
  line(heartX, heartBottomY, heartX, heartBottomY-heartSize*.75);

  //dark hearts have light outlines and vice versa

  //left half of heart
  curveVertex(heartX, heartBottomY+heartSize); //anchor point
  curveVertex(heartX, heartBottomY); //bottom tip
  curveVertex(heartX - heartSize/2, heartBottomY-heartSize/1.5); //left edge
  curveVertex(heartX - heartSize/3, heartBottomY-heartSize); //top of left edge
  curveVertex(heartX, heartBottomY-heartSize*.75); //top middle dip
  curveVertex(heartX, heartBottomY); //guiding point

  //right half of heart
  curveVertex(heartX, heartBottomY);
  curveVertex(heartX, heartBottomY-heartSize*.75);
  curveVertex(heartX + heartSize/3, heartBottomY-heartSize);
  curveVertex(heartX + heartSize/2, heartBottomY-heartSize/1.5);
  curveVertex(heartX, heartBottomY);
  curveVertex(heartX, heartBottomY + heartSize);

This code modifies the heart drawing logic: instead of always drawing in the center of the screen, the location of the heart is determined by the heartX and heartBottomY variables. Instead of using the width and height variables, the size of the heart is determined by the heartSize variable. Try feeding in different hard-coded values to those variables to see what they do.

From there, it’s just a matter of putting the code inside the draw() function so it’s called 60 times per second, and then choosing random values for the above variables. Now we get random hearts!

random hearts

Code Editor

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

Tweak Ideas

  • Change the color of the heart. Make it a random color!
  • Add somebody’s name to the middle of the heart. Send them a nerdy Valentine!

random hearts random hearts random hearts

Creating Functions Examples


Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!