Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Color Gradients in p5.js Through Interpolation and Canvas Contexts

Tech 1

The p5.js framework includes robust utilities for managing color transitions, with lerpColor() acting as the core mechanism for interpolating between two distinct hues. This function evaluates a normalized parameter ranging from 0.0 to 1.0 and returns a blended color proportionally positioned between the start and end values.

To demonstrate basic interpolation, define two base colors and compute a midpoint value. The resulting output can be applied directly to drawing operations.

function setup() {
  createCanvas(320, 180);
  noStroke();

  const originShade = color(200, 50, 50);
  const targetShade = color(50, 50, 200);
  const midpoint = 0.5;
  
  const blended = lerpColor(originShade, targetShade, midpoint);

  background(30);
  fill(originShade);
  rect(40, 40, 60, 100);

  fill(blended);
  rect(130, 40, 60, 100);

  fill(targetShade);
  rect(220, 40, 60, 100);
}

Constructing a linear gradient manual involves partitioning the canvas into narrow vertical strips. By incrementally adjusting the interpolation factor for each segment, a continuous color shift emerges across the surface. Increasing the segment count while reducing their individual width improves visual smoothness.

function setup() {
  createCanvas(400, 300);
  noStroke();
  background(20);

  const firstTone = color(255, 140, 0);
  const lastTone = color(0, 140, 255);
  const totalStrips = width;

  for (let step = 0; step < totalStrips; step++) {
    const progression = step / (totalStrips - 1);
    const currentHue = lerpColor(firstTone, lastTone, progression);
    fill(currentHue);
    rect(step, 0, 1, height);
  }
}

While strip-based rendering works, it introduces unnecessary draw calls and limits gradient directionality. For optimized and flexible results, bypass the p5.js wrapper and interact directly with the native HTML5 Canvas rendering context available via drawingContext. This approach supports multi-stop linear gradients with arbitrary coordinates.

function setup() {
  createCanvas(450, 450);
  noStroke();
  background(15);

  const surface = drawingContext;
  const gradientObj = surface.createLinearGradient(0, 0, width, height);
  
  gradientObj.addColorStop(0.0, "rgb(255, 80, 80)");
  gradientObj.addColorStop(0.5, "rgb(120, 255, 120)");
  gradientObj.addColorStop(1.0, "rgb(80, 80, 255)");

  surface.fillStyle = gradientObj;
  surface.fillRect(0, 0, width, height);
}

Radial transitions follow an identical architectural pattern, requiring only a switch to the createRadialGradient method. This function accepts two focal points and their respective radii to define the gradeint cone, allowing precise control over the diffution area.

function setup() {
  createCanvas(450, 450);
  noStroke();
  background(15);

  const ctx = drawingContext;
  const centerX = width * 0.5;
  const centerY = height * 0.5;
  const innerRadius = 40;
  const outerRadius = 180;

  const radialPattern = ctx.createRadialGradient(
    centerX, centerY, innerRadius,
    centerX, centerY, outerRadius
  );

  radialPattern.addColorStop(0, "rgba(255, 200, 50, 1)");
  radialPattern.addColorStop(1, "rgba(50, 100, 255, 0)");

  ctx.fillStyle = radialPattern;
  ctx.fillRect(0, 0, width, height);
}
Tags: p5.jsCanvas

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.