githubEdit

Canvas

The OSL canvas commands are a set of commands that internally store images that can be easily written to and read from. The canvas element is primarily used in situations where the user will directly be interacting with an image, such as drawing programs or image editors.

A canvas can be initialized using one of two ways:

// width - the width of the canvas, in pixels
// height - the height of the canvas, in pixels
// background - the background color of the canvas (ex. #fff)
canvas myCanvas @= canvas(width, height, background)

// url - a DataURI to load as the canvas content, stretched to fit
canvas myCanvas @= canvas.fromURL(url, width, height)

Canvas Type

Canvases also have their own type, so using Typeof will give you "canvas"

canvas myCanvas @= canvas(100, 100, "#fff")

// will log true
log typeof(myCanvas) == "canvas"

Writing to the Canvas

OSL provides many methods for writing to the canvas. The most primitive of these write to a single pixel.

Shapes

The canvas provides methods to draw lines, rectangles, and triangles. When drawing shapes, the cursor's color is used as the fill color (this can be set with the color/colour/c command). They use the same coordinate system as setPixelAt, where (0, 0) is in the center of the canvas. It's worth noting that these methods are not pixel perfect; at smaller canvas sizes they may appear blurry.

Stamping

Canvases can also apply other images onto themselves using DataURIs. The image is stretched to fit the provided dimensions.

Reading the Canvas

OSL provides several methods for reading canvas data.

To get the entire canvas as a DataURI, use toURL().

Methods can also be used to find the dimensions of the canvas.

Finally, methods can be used to find the color of specific pixels. These serve as the inverses of setPixel and setPixelAt.

Managing Canvases

Most canvas management is handled internally; all stored canvases are deleted when the window is closed, and canvases are stored in such a way that prevents interference from other scripts. However, sometimes the need arises to handle these interactions manually. OSL exposes several commands for deleting and resizing canvases.

Deleting/Clearing Canvases

The delete and clear methods function very similarly, with the key difference being that delete entirely removes the canvas from memory, while clear simply erases its content, while still allowing it to be written to.

The fill method allows you to clear a canvas with a specific colour

Resizing Canvases

The stretch method will stretch the current content (hence the name) to fit the new canvas size specified in the stretch arguments.

Example: Drawing a Checker Pattern

Last updated