Solve It
In this example, we are going to create an image that looks like two planets in space, using mathematical functions.
The main idea is to map the value of one aspect of the picture into another aspect of the picture. In this case, we are going to map the distance between points into red, green, or blue values. We need to begin by writing a function that gives us the distance between two points (we'll just look up the equation and turn it into code). Now, for the main algorithm, we start by creating a blank image and writing the loop that will let us fill in the color values for each pixel.
The "planet" effect is achieved by deciding on a point for the planets to be, then coloring the areas around the planets by mapping the distance from the planet to a color brightness. The closer the pixel is to the planet, the closer the color of the pixel is to the planet's color. In this example, we have chosen the point (100,100) to be a red planet and (200,200) to be a green planet.
We can use the same idea to make a gradient effect in the background. We know that the main diagonal of an image is the points where the x value equals the y value. We can get an interesting visual effect by using the difference between the x and y values to map to the blue value of the pixels. The image appears darker near the main diagonal.
Finally, we add "stars" by randomly coloring some pixels white.
As you look at this code example, you may ask yourself, "Why did they use 1.5 there? Why not 1.2 or 1.7?" The answer to this type of question is often not very mathematical. Instead, it was because we played with the code until we got the visual effect we liked. We encourage you to tweak both this code example and your own code to see what difference it makes in the image. See if you can figure out why the image looks the way it does based on your change and which version you like the best.
Code It
See It
Available Images
Drop your images onto the area above to make it available within your code editor on this page. Note: your images will not be uploaded anywhere, they will stay on your computer.
