100 100 moveto 200 300 lineto stroke

In the last chapter, we have created the white page where we can paint on. In this chapters we are starting to draw lines. The process in PostScript is always defined points that form a path of a polygon (moveto, lineto), than either draw the border of the polygon (stroke) or paint the polygon (fill) and then finish the page (shwopage).

While building the path, the interpreter needs a place to store the path and also all other parameters that could be of importance (color, stroke width). We therefore add to the context a graphics object to hold that state.

context.graphics = { path: [], current: [], color: [0, 0, 0, 255]};

Javascript

And we adapt the console to show the graphics state.

Javascript

We build our first operators to create paths.

  • x y moveto
  • x y rmoveto
  • x y lineto
  • x y rlineto
  • closepath
  • g setgray

The path we constructs is an array of subpaths, which contain line segments. Each line segment has a type, then coordinates. For the moment, we only have a straight lines, later we will also have curved lines.

Why the subpaths: There are some graphics elements which have subpaths like the letter P oder the letter A. Subpaths will later allow in fill to exclude regions from fill.

Javascript

We can now build a path of two triangles. The first triangle is a simple triangle with absolute positions. We then define an operator that uses relative triangles. This allows us to position the same triangle over the page.

Javascript Editor

We have the paths, now we need to draw the pixels. We define the operators to draw and to output the page.

  • stroke
  • showpage

We have to draw a line from x0,y0 to x1,y1. We use linear interpolation. How many points do we need. We want to be sure that every x and every y is drawn, so we define the number of steps as the maximum of the horizontal and the vertical distance.

Javascript

We add stroke to the PostScript code

Javascript Editor

That looks already very interesting. We did draw all paths in a single stroke. This is possible, but normally we draw it seperately, especially if they have different colors so normally we would stroke each path separately.

Javascript Editor

We can draw complex things like letters

Javascript Editor

We have made big steps today. But we are only drawing the edges. In the next chapter, we will introduce the scanfill algorithm to fill a a path.

The codebase is now 1125 lines ps20240713.js

My Journey to PostScript