Skip to content

Drawing

The drawing API is what application code uses. It is written once, in pollock/draw, on top of the backend primitives described in The context, so everything here works with every backend. import pollock includes all of it.

Every proc here is generic over C: RenderContext: the first argument is ctx: var C.

Shapes

A shape is anything with toPath and boundingBox. These come with pollock:

Shape Constructors
Rect rect(x0, y0, x1, y1), rect(origin, size), rectXywh(x, y, width, height), rectFromPoints(a, b)
RoundedRect roundedRect(rect, radius), roundedRect(x0, y0, x1, y1, radius)
Circle circle(center, radius), circle(x, y, radius)
Ellipse ellipse(center, rx, ry)
Line line(p0, p1), line(x0, y0, x1, y1)
Arc arc(center, radius, startAngle, sweepAngle), arc(center, radii, startAngle, sweepAngle, rotation = 0)
BezPath newPath() then moveTo, lineTo, quadTo, cubicTo, arcTo, closePath; polygonPath(points)

A BezPath is a sequence of PathEl values. Build one like this:

var p = newPath()
p.moveTo 10, 10
p.lineTo 100, 10
p.quadTo point(120, 50), point(100, 90)
p.cubicTo point(80, 120), point(30, 120), point(10, 90)
p.arcTo 40.0, point(10, 10)
p.closePath()

A subpath that is only a moveTo draws nothing. One whose segment has zero length (moveTo p then lineTo p) draws a dot when stroked with round or square caps, as in SVG.

extend appends one path to another, which is how you make a path with several subpaths (rings, holes). transform(affine, path) returns a transformed copy, boundingBox the exact bounds of the curves, flatten(path, tolerance) the polylines within tolerance of the curves, and area the signed area.

Arcs

arcTo(radii, rotation, largeArc, sweep, to) adds an elliptical arc the way SVG's A command does: from the current point to to, along an ellipse with radii whose x axis is turned by rotation radians. Two ellipses of that shape pass through both points, and each is cut in two by them, so four arcs are possible: largeArc picks the longer ones and sweep the one that turns clockwise on screen (the positive angle direction). Radii too small to reach both points are scaled up until they just do, so arcTo(radius, to), the circular shorthand, draws a half circle when the radius is half the distance. A zero radius draws a straight line, and an arc that ends exactly where it starts draws nothing. Arcs stay arcs under transform, and the SVG backend writes them as they are.

An Arc is the shape form, in center parameterization: arc(center, radius, startAngle, sweepAngle) is the piece of the circle from startAngle through sweepAngle (a negative sweep goes the other way, and 2 * PI is the whole circle). The elliptical form takes radii and the ellipse's rotation. Angles are the ellipse's parameter, so pointAt(arc, angle) is center + rotate(rotation) * (rx * cos(angle), ry * sin(angle)); startPoint and endPoint are the ends. toArc(el, start) converts an arc element into an Arc, and toCubics turns an Arc, an element or a whole path's arcs into cubic curves, for code that only handles those.

Rectangles have the usual helpers: width, height, size, origin, center, union, intersect, contains, inflate, inset, translate, normalized, roundOut, isEmpty.

Colors and paints

A Color is sRGB with straight alpha, components in 0..1: rgb(r, g, b), rgba(r, g, b, a), rgb8(r, g, b), rgba8(r, g, b, a), gray(level), parseHex("#rrggbb"), and withAlpha to change the alpha. The constants black, white, red, green, blue, yellow, cyan, magenta and transparent are there too.

A Paint is what a fill or stroke is painted with:

  • solid(color). Everywhere a Paint is accepted, a Color works too.
  • linearGradient(p0, p1, c0, c1) or linearGradient(p0, p1, stops): from p0 to p1 in user space (that is, under the current transform).
  • radialGradient(center, radius, c0, c1) or radialGradient(center, radius, stops).

Stops are stop(offset, color) with offsets in 0..1, in order. The optional extend argument (exPad, exRepeat, exReflect) says what happens outside 0..1. A linear gradient whose two points are the same, or a radial one with no radius, paints the color of its last stop.

Filling and stroking

proc fill(ctx, shape, paint: Paint, rule = frNonZero)
proc fill(ctx, shape, color: Color, rule = frNonZero)

Fills the shape. rule is frNonZero or frEvenOdd, which differ for self-intersecting paths and for paths with several subpaths.

proc stroke(ctx, shape, paint: Paint, width = 1.0)
proc stroke(ctx, shape, color: Color, width = 1.0)
proc stroke(ctx, shape, paint: Paint, style: StrokeStyle)
proc stroke(ctx, shape, color: Color, style: StrokeStyle)

Strokes the outline. The short forms stroke with butt caps and miter joins. A StrokeStyle has width, cap (lcButt, lcRound, lcSquare), join (ljMiter, ljRound, ljBevel), miterLimit, dashes (on and off lengths in user units) and dashOffset:

strokeStyle(width = 3, cap = lcRound, join = ljRound, dashes = [6.0, 3.0])

A zero-length on entry draws a dot when the cap is round or square, so dashes = [0.0, 6.0] with cap = lcRound gives a dotted line that starts with a dot. A miter limit below 1 bevels every join.

Stroke width is in user space: scale the context by two and a 1-wide stroke becomes 2 pixels wide.

Clipping

proc clip(ctx, shape, rule = frNonZero)

Restricts later drawing to the inside of shape, intersected with any clip already in place. There is no way to remove a clip except restore, so clips almost always go inside withSave or withClip.

Transforms

proc translate(ctx, x, y)
proc translate(ctx, v: Vec2)
proc scale(ctx, s)
proc scale(ctx, sx, sy)
proc rotate(ctx, radians)
proc rotateAbout(ctx, radians, center)

Each one multiplies the current transform. ctx.transform(affine) applies any Affine, and ctx.currentTransform reads it back. Positive rotation turns clockwise on the screen, because y points down.

Affine values compose with *, where a * b applies b first: translate(100, 0) * rotate(0.5) rotates, then moves. inverse, apply (also spelled m * point), determinant, scaleFactor (the average stretch) and maxScale (the largest stretch in any direction) are there for your own math.

Scopes

template withSave(ctx, body)
template withTransform(ctx, affine, body)
template withClip(ctx, shape, body)

Each runs body between save and restore, so the transform and the clip go back to what they were, even if body raises. withTransform applies affine first and withClip clips to shape first.

ctx.withTransform(translate(50, 50) * scale(2)):
  ctx.withClip(circle(0, 0, 20)):
    ctx.fill(rect(-20, -20, 20, 20), blue)

Images

An ImageData is pixels in memory: width, height, a format (ifGray8, ifRgb8, ifRgba8, ifRgba8Premul) and the bytes. Make one with newImage(width, height, format) and set pixels with img[x, y] = color, or load a PNG with readPng(path) (decodePng(bytes) for data already in memory).

proc drawImage(ctx, image, at: Point, interp = ipBilinear)
proc drawImage(ctx, image, dst: Rect)
proc drawImage(ctx, image, dst: Rect, interp: Interpolation)

Draws the image at its natural size, or stretched into dst. ipNearest keeps pixels sharp, ipBilinear smooths them. The current transform and clip apply.

Text

proc drawText(ctx, layout: TextLayout, at: Point)
proc drawText(ctx, layout: TextLayout, x, y: float64)
template drawText(ctx, text: string, style: TextStyle, at: Point)

Draws laid-out text with the start of its baseline at at, each run in its own paint; the template lays the text out with the context's engine first. Fonts, styles, layouts and engines are described in Text.

Clearing and finishing

ctx.clear(color) paints the whole target, ignoring the transform and the clip. ctx.finish() returns a RenderResult whose ok is false if any drawing call failed since the last finish; backends never raise from drawing calls.