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.
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.