Ray Tracing 001The First Image

Summary

  • First simple image with a color gradient.
  • Image stored in a text-based file format (PPM).

Simple Image with PPM

The Portable PixMap (PPM) is a simple text-based image format. No special libraries needed: pixel data is written to a text-file.

Each line in the file represents a pixel's RGB color in three integer values from 0 to 255. The lines draw the image from top to bottom and left to right, where the first line is the origin at the top left corner of the image.

This is essentially the Hello World app of computer graphics without any external dependencies.

Click to view C++ source code

Simple Image with Javascript and Canvas

The Javascript code is almost identical with the C++ code but instead of a PPM file it renders each pixel in a 200x100 canvas element.

To keep the color gradient in the same direction as the PPM I reversed the y-direction in the fillRect() call.

Click to view Javascript source code

Loading...

Figure RT001: Simple canvas image rendered with Javascript

Simple Image with Python

The Python code below is not all that different as well. Although not really necessary at this stage, I defined a main() function and call it if the file is executed directly. The __name__ variable is a special variable that's set to __main__ if the file is executed as the main program. If the file is being imported from another module, __name__ will be set to the module's name.

Python3 introduced f-strings which allow me to embed variables in curly braces, similar to Javascript's template literals. The string doesn't have to include a line-break at the end. The print function adds it automatically, unless I call the function with an additional end='' argument.

Another thing to note is that the end value in the range() function is not included. For example, range(3,0,-1) returns 3 2 1, but not 0; and range(0,3,1) returns 0 1 2, but not 3.

Click to view Python source code

Links