Rethinking stroke

The first version of stroke draws only lines of one pixel width.

Javascript Editor

PostScript can however stroke lines of any width if you set it with the operator setlinewitdh. We add the linewidth to the context initialization and create the operators setlinewidth, currentlinewidth and also currentgray. The latter allow us to inspect the graphic state. Note there is no native PostScript operator currentpath, probably to copy protect the fonts which are also paths.

Javascript

Now we make a first naive approach with an operator we call stroke2. New repeat horizontally for each pixel.

Javascript

As you can understand, this will not work for lines that are not vertical.

Javascript Editor

We have to go down to the schoolbooks and do the geometry. The definition of PostScript is: "stroke paints all points whose perpendicular distance from the current path in user space is less than or equal to one-half the absolute value of num."

Instead of one line we have two parallel lines. We can close them and simulate the linewidth by filling the path.

First we need to add the atan operator to calculate the angle. atan returns the angle based on dy and dx and works also when dx is 0 and tan(a) would actually be infinity. Javascript knows this function also under the name Math.atan2(num,denum), so the operator just exposes the function and handles the scale (pi / 180).

Javascript

We can write this directly in PostScript. We will have to do this separately for each subpath. We create two paths on each side of the middle path. Then we join the end of the first path with the reverse of the second path and close the path.

Javascript

Which works partially. The width is there in all directions, but we have problems went the lines join.

Javascript Editor

The problems are the crossing paths. When paths cross, the scanfill algorithm will not work properly. We to join the path segments on each side properly.

We calculate the connection points of the two lines, having 2 points for each line. It is the formula in Line-line intersection

So we rewrite

Javascript

Javascript Editor

Congratulations, if you followed until here. The codebase has now 1416 lines and we have implemented 58 operators (out of more than 400 built in operators). ps20240726.js

My Journey to PostScript