Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Mastering Ellipses in p5.js: From Fundamentals to Creative Applications

Tech 1

Ellipses are versatile shapes—think of them as the flexible relatives of circles. They can be wide, narrow, horizontal, or vertical, making them essential elements in creative projects. The ellipse() function in p5.js simplifies drawing various ellipses. This guide covers everything from the basics to advanced creative uses.

Understanding ellipse(): The Ellipse's Identity

What is ellipse()?

ellipse() is a p5.js function designed for drawing ellipses. An ellipse can be visualized as a stretched circle; when its width and height are equal, it becomes a perfect circle (which is why circle() is essentially a special case of ellipse()).

In creative work, ellipses are widely used for depicting moons, eggs, leaves, faces, buttons, and even as foundational elements in abstract art.

Core Parameters: Four Numbers Define the Shape

The basic syntax of ellipse() requires only four essential parameters:

ellipse(x, y, w, h)

Parameter explanation:

  • x: Horizontal position of the ellipse's center (greater values move it right).
  • y: Vertical position of the ellipse's center (greater values move it down).
  • w: Width of the ellipse (maximum horizontal distance).
  • h: Height of the ellipse (maximum vertical distance).

Example: ellipse(200, 150, 100, 60) draws an ellipse centered at (200,150) with a width of 100 and height of 60.

Aspect Ratio Determines Shape

The proportions of width (w) and height (h) define the ellipse's form:

  • When w > h: Horizontal ellipse (e.g., a lying egg).
  • When w < h: Vertical ellipse (e.g., a standing egg).
  • When w = h: Perfect circle (identical to circle()).

Drawing You're First Ellipse

Start with a basic example to understand how parameters work.

function setup() {
  // Create a 400×400 canvas
  createCanvas(400, 400);
  // Light gray background (220 is light gray, 0 is black, 255 is white)
  background(220);
}

function draw() {
  // Draw an ellipse: center (200,200), width 200, height 100 (horizontal ellipse)
  ellipse(200, 200, 200, 100);
  
  // Draw a smaller ellipse: center (200,200), width 80, height 150 (vertical ellipse)
  fill(255, 200, 0); // Fill with yellow (RGB values)
  ellipse(200, 200, 80, 150);
}

On a light gray canvas, you'll see a black-outlined horizontal ellipse (like a flatened circle) overlapped by a yellow vertical ellipse (like a stretched circle).

  • fill(255, 200, 0) sets the interior color to yellow (using RGB values).
  • Both ellipses share the same center point (200,200) but have different dimensions, creating an intersecting effect.

Advanced: Styling Ellipses

Similar to circles, you can use p5.js styling functions to customize ellipses with colors, borders, and more.

Common Styling Functions:

  • fill(r, g, b): Sets the fill color (RGB values, 0-255); noFill() removes fill.
  • stroke(r, g, b): Sets the border color; noStroke() removes the border.
  • strokeWeight(weight): Sets border thickness (larger values mean thicker borders).
function setup() {
  createCanvas(400, 300);
  background(255); // White background
  noLoop(); // Draw once without refreshing
}

function draw() {
  // 1. Ellipse with no fill, thick red border
  stroke(255, 0, 0); // Red border
  strokeWeight(5); // 5-pixel border thickness
  noFill(); // No interior fill
  ellipse(100, 100, 120, 80);
  
  // 2. Ellipse with blue fill, no border
  noStroke(); // Remove border
  fill(0, 0, 255); // Blue fill
  ellipse(250, 100, 100, 100); // Equal width and height, making it a circle
  
  // 3. Ellipse with green fill, thin black border
  stroke(0); // Black border
  strokeWeight(2); // Thin border
  fill(0, 255, 0); // Green fill
  ellipse(175, 220, 180, 90);
}

On a white canvas, three ellipses demonstrate different styles: border-only, fill-only, and fill with border.

Changing Ellipse Positioning

By default, ellipse(x, y, w, h) uses x and y as the center point. The ellipseMode() function allows you to adjust this for more flexibility.

Common ellipseMode() Options:

  • ellipseMode(CENTER): Default mode; x and y are the center point (recommended for beginners).
  • ellipseMode(CORNER): x and y are the top-left corner coordinates (similar to rectangle positioning).
function setup() {
  createCanvas(400, 200);
  background(240);
  noLoop();
  
  // Draw reference lines for clarity
  stroke(200);
  line(0, 100, 400, 100); // Horizontal line
  line(200, 0, 200, 200); // Vertical line
  
  // 1. Default mode (CENTER): x,y is the center
  fill(255, 150, 150, 150); // Semi-transparent pink
  ellipseMode(CENTER);
  ellipse(200, 100, 100, 60);
  text("CENTER mode", 150, 40);
  
  // 2. CORNER mode: x,y is the top-left corner
  fill(150, 150, 255, 150); // Semi-transparent blue
  ellipseMode(CORNER);
  ellipse(200, 100, 100, 60);
  text("CORNER mode", 150, 180);
}

The pink ellipse centers at the intersection (200,100), while the blue ellipse uses it as the top-left corner, illustrating the difference between positioning modes.

Animating Ellipses: Simple Examples

Ellipse parameters (position, size, color) can be controlled with variables. Combined with the automatic refresh of the draw() functon, this enables animation.

Swinging Ellipse (Simulating a Pendulum)

let swingAngle = 0; // Angle variable for swinging motion

function setup() {
  createCanvas(400, 300);
}

function draw() {
  background(135, 206, 235); // Sky blue background
  
  // Calculate ellipse's x-coordinate using sine function for left-right swing
  let xPos = 200 + sin(swingAngle) * 100;
  // y-coordinate fixed at 150
  let yPos = 150;
  
  // Draw the swinging ellipse
  fill(255, 215, 0); // Gold color
  noStroke();
  ellipse(xPos, yPos, 80, 50);
  
  // Increment angle for continuous animation (0.05 controls speed)
  swingAngle += 0.05;
}
  • sin(swingAngle) produces values between -1 and 1, multiplied by 100 to swing the x-coordinate between 100 and 300.
  • Each draw() call increases swingAngle by 0.05, creating smooth motion.
  • The background is redrawn each frame to prevent trailing effects.

Breathing Effect (Size Variation)

let ellipseSize = 50; // Initial size
let isGrowing = true; // Tracks growth direction

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(0); // Black background
  
  // Draw a purple ellipse centered on the canvas
  fill(128, 0, 128); // Purple
  noStroke();
  ellipse(200, 200, ellipseSize, ellipseSize * 0.7); // Height is 70% of width
  
  // Control size changes for breathing effect
  if (isGrowing) {
    ellipseSize += 1; // Increase size
    if (ellipseSize > 200) isGrowing = false; // Switch to shrinking at max size
  } else {
    ellipseSize -= 1; // Decrease size
    if (ellipseSize < 50) isGrowing = true; // Switch to growing at min size
  }
}

A purple ellipse on a black background expands and contracts like breathing, maintaining a constant width-to-height ratio (always a horizontal ellipse).

Comprehensive Example: Floating Balloon Bouquet

Create a set of floating balloons using ellipses, each with strings and subtle motion.

  1. Design Elements:
    • Each balloon is a vertical ellipse (height slightly greater than width), mimicking real balloons.
    • Add semi-transparent white highlight ellipses for a 3D effect.
    • Use brown lines as strings, converging at a central node to form a bouquet.
  2. Ellipse Parameter Application:
    • Vary balloon sizes using w (width) and h (height) parameters for diversity.
    • Position highlight ellipses offset from the main balloon center to simulate light reflection.
    • Represent the string node with a circular ellipse (w = h), showing the relationship between ellipses and circles.
  3. Animation Effects:
    • Use sin() and cos() functions for natural left-right and up-down floating motions.
    • Assign different swing speeds (speed parameter) to each balloon to avoid uniformity.
    • Limit floating amplitude to ±15 pixels for cohesive movement.
  4. Coding Techniques:
    • Store balloon properties in an array of objects (balloons) for easy management and drawing.
    • Loop through the array to draw all balloons, minimizing code repetition.
    • Use transparency (fourth parameter in RGBA) for highlights to enhance visual depth.
// Array to store balloon properties
let balloons = [];

function setup() {
  createCanvas(500, 600);

  // Initialize five balloons with varied positions, sizes, and colors
  balloons = [
    {xPos: 150, yPos: 300, width: 80, height: 100, color: [255, 99, 71], swingPhase: 0, swingSpeed: 0.03},
    {xPos: 220, yPos: 250, width: 70, height: 90, color: [60, 179, 113], swingPhase: 1, swingSpeed: 0.02},
    {xPos: 300, yPos: 280, width: 90, height: 110, color: [70, 130, 180], swingPhase: 2, swingSpeed: 0.04},
    {xPos: 180, yPos: 320, width: 60, height: 80, color: [255, 165, 0], swingPhase: 3, swingSpeed: 0.025},
    {xPos: 350, yPos: 310, width: 75, height: 95, color: [147, 112, 219], swingPhase: 4, swingSpeed: 0.035}
  ];
}

function draw() {
  background(240); // Light gray background

  // Draw the string convergence point
  let nodeX = 250;
  let nodeY = 400;
  fill(139, 69, 19); // Brown
  ellipse(nodeX, nodeY, 10, 10); // String node

  // Loop to draw each balloon
  for (let i = 0; i < balloons.length; i++) {
    let balloon = balloons[i];

    // Update balloon swing position
    balloon.swingPhase += balloon.swingSpeed;
    let floatX = sin(balloon.swingPhase) * 15; // Horizontal swing
    let floatY = cos(balloon.swingPhase * 0.8) * 10; // Vertical float

    // Draw balloon body (ellipse)
    fill(balloon.color);
    noStroke();
    ellipse(balloon.xPos + floatX, balloon.yPos + floatY, balloon.width, balloon.height);

    // Draw highlight for 3D effect
    fill(255, 255, 255, 150); // Semi-transparent white
    ellipse(balloon.xPos + floatX - balloon.width/6, balloon.yPos + floatY - balloon.height/6, balloon.width/4, balloon.height/4);

    // Draw connecting string
    stroke(139, 69, 19);
    strokeWeight(2);
    line(balloon.xPos + floatX, balloon.yPos + floatY + balloon.height/2, nodeX, nodeY);
  }

  // Draw ground
  fill(184, 134, 11); // Earth tone
  rect(0, height - 50, width, 50);
}
Tags: p5.js

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.