VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-create-a-rainbow-disc-using-p5-js/

⇱ How to create a rainbow disc using p5.js ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to create a rainbow disc using p5.js ?

Last Updated : 23 Jul, 2025

In this article, we are going to see how we can create a rainbow disc using p5.js. p5.js is a JavaScript library that makes it easy to create interactive graphics, and it is well-suited for visualizations of all kinds, including rainbows. This article will show you how to create a rainbow using p5.js.

Approach:

  • Create an HTML file and include the p5.js library.
  • In the setup() function:
    • Create a canvas with the desired size using the createCanvas(width, height) function.
    • Set the color mode to HSB using the color mode (mode) function.
    • Create an array to store the colors, in this case, the array will have 360 elements, one for each hue value.
    • Use a for loop to iterate through the hue values from 0 to 359.
    • For each iteration, use the color(hue, saturation, brightness) function to create a color and add it to the array.
    • Set the saturation and brightness to a fixed value (100)
  • In the draw() function:
    • Use a for loop to iterate through the array of colors.
    • For each color in the array, use the fill(color) function to set the current color as the fill color.
    • Use the rect(x, y, width, height) function to create a rectangle with the current color and the desired width and height.
    • To create the rainbow effect, place each rectangle next to the other by using the iteration variable to calculate the x-coordinate of the rectangle.

Prerequisite: These are the list of all the functions used in the example code.

  • createCanvas(width, height): It creates a canvas element in the HTML file with the specified width and height.
  • colorMode(mode): Sets the colour mode for the program, in this case, it's set to HSB (hue, saturation, brightness) mode.
  • color(hue, saturation, brightness): Creates a colour using HSB values, where hue is a value from 0 to 360, saturation is a value from 0 to 100, and brightness is a value from 0 to 100.
  • fill(color): Sets the colour to be used for filling shapes.
  • rect(x, y, width, height): Creates a rectangle shape with the specified x and y coordinates, width, and height.

Note that the setup() and draw() functions are also used, but they are built-in functions in p5.js and are called automatically. setup() runs once before the first frame is drawn, while draw() runs continuously, once per frame, after the setup() function.

Example:  In this example we will create a rainbow palette, using the p5.js.

Output:

👁 Image
Comment