Plask Documentation


Table Of Contents


Plask

The plask module is the core for all of Plask's functionality. It would generally be imported like:

var plask = require('plask');

2D Vector Graphics

Plask supports drawing 2D vector graphics, using the Skia graphics library. Support exists for drawing graphics on screen, or saving them to image files, PDF files, or transfering them to OpenGL textures.

The SkCanvas class represents the 2D surface that Skia draws to. This can be attached to a window, an offscreen bitmap surface, or a surface used for writing PDFs.

The graphics settings (colors, sizes, etc) are managed by an SkPaint object.

Complex paths can be created and managed with an SkPath object.

SkCanvas.create(width, height)

Create an offscreen bitmap canvas, with four 8-bit channels per pixel (RGBA).

The width and height are the canvas size in pixels.

SkCanvas.createForPDF(page_width, page_height, content_width, content_height)

Create a canvas capable of rendering to a PDF file. This is not a bitmap, and cannot be used with the APIs that expect a rendered bitmap. When using this type of surface, the drawing commands are translated to PDF, and the PDF is renderer resolution independent (vector).

The page_width and page_height specify the size of the page in points. For example US letter would be 612x792 and A4 595x842. The content_width and content_height specify the size (in points) of the content within the page. If the content sizes are not specified, they default to the page size.

SkCanvas.createFromImage(path)

Create a canvas from reading an image off disk. The canvas size will be the size of the image, and the image will be copied onto the canvas.

It is generally a good idea to use an absolute pathname for path.

var plask = require('plask');
var path = require('path');

// Loads the image file tex.png in the same directory as our script.
var image = plask.SkCanvas.createFromImage(path.join(__dirname, 'tex.png'));

SkCanvas#clipPath(path)

Set the clipping path to the SkPath object path. Setting the clipping path will prevent any pixels to be drawn outside of this path.

The save() and restore() functions are the best way to manage or reset the clipping path.

SkCanvas#clipRect(left, top, right, bottom)

Set the clipping path to the rectangle of the upper-left and bottom-right corners specified. Setting the clipping path will prevent any pixels to be drawn outside of this path.

The save() and restore() functions are the best way to manage or reset the clipping path.

SkCanvas#dispose

Clear the native memory (pixels) and objects associated with this canvas. This gives you greater control over memory management, instead of having to wait for the garbage collector to clean up the object.

Once diposed, it is illegal and will crash if the canvas object is used.

SkCanvas#drawCanvas(paint, source, dst_left, dst_top, dst_right, dst_bottom, src_left, src_top, src_right, src_bottom)

Draw one canvas on to another canvas. The paint object controls settings involved in the drawing, such as anti-aliasing. The source parameter is the source canvas to be drawn from. The first four parameters define the rectangle within the destination canvas that the image will be drawn. The last four parameters specify the rectangle within the source image. This allows for drawing portions of the source image, scaling, etc.

The last four parameters are optional, and will default to the entire source image (0, 0, source.width, source.height).

var img = plask.SkCanvas.createFromImage('tex.png');  // Size 100x150.
// Draw the texture image scaled 2x larger.
canvas.drawCanvas(paint, img,
                  0, 0, 200, 300,  // Draw at (0, 0) size 200x300.
                  0, 0, 100, 150)  // Draw the entire source image.

SkCanvas#drawCircle(paint, x, y, radius)

Draw a circle centered at (x, y) of radius radius.

SkCanvas#drawColor(r, g, b, a, blendmode)

Fill the entire canvas with a solid color. If blendmode is not specified, it defaults to SrcOver, which will blend with anything already on the canvas.

Use eraseColor() when you do not need any alpha blending.

SkCanvas#drawLine(paint, x0, y0, x1, y1)

Draw a line between (x0, y0) and (x1, y1).

SkCanvas#drawPaint(paint)

Fill the entire canvas with a solid color, specified by the paint's color and blending mode.

SkCanvas#drawPath(paint, path)

Draw an SkPath. The path will be stroked or filled depending on the paint's style (see SkPaint#setStyle).

SkCanvas#drawPoints(paint, mode, points)

An optimized drawing path for many points, lines, or polygons with many points. The mode parameter is one of kPointsPointMode, kLinesPointMode, or kPolygonPointMode. The points parameter is an array of points, in the form of [x0, y0, x1, y1, ...].

SkCanvas#drawRect(paint, left, top, right, bottom)

Draw a rectangle specified by the upper-left and bottom-right corners.

SkCanvas#drawRoundRect(paint, left, top, right, bottom, xradius, yradius)

Draw a rectangle with rounded corners of radius xradius and yradius.

SkCanvas#drawText(paint, str, x, y)

Draw the string str with the bottom left corner starting at (x, y).

SkCanvas#drawTextOnPathHV(paint, path, str, hoffset, voffset)

Draw the string str along the path path, starting along the path at hoffset and above or below the path by voffset.

SkCanvas#eraseColor(r, g, b, a)

Replace the entire canvas with a single color and alpha value. No blending occurs.

SkCanvas#resetMatrix()

Reset the transform matrix to the identity.

SkCanvas#restore()

Restore the transform matrix from the matrix stack.

SkCanvas#rotate(degrees)

Rotate the canvas by degrees degrees (not radians).

SkCanvas#save()

Save the transform matrix to the matrix stack.

SkCanvas#scale(x, y)

Scale the canvas by x and y.

SkCanvas#skew(x, y)

Skew the canvas by x and y.

SkCanvas#translate(x, y)

Translate the canvas by x and y.

SkCanvas#writeImage(typestr, filename)

Write the current contents of the canvas as an image named filename. The typestr parameter selects the image format. Currently only 'png' is supported.

SkCanvas#writePDF(filename)

Write the contents of a vector-mode SkCanvas (created with createForPDF) to the file named filename.

SkPaint#reset()

Reset the paint to the default settings.

SkPaint#getFlags()

Return the paint flags.

SkPaint#setFlags(flags)

Set the paint flags, such as whether to perform anti-aliasing.

// The follow flags are supported.  They should be OR'd together to set
// multiple settings.
//   kAntiAliasFlag
//   kFilterBitmapFlag
//   kDitherFlag
//   kUnderlineTextFlag
//   kStrikeThruTextFlag
//   kFakeBoldTextFlag
//   kLinearTextFlag
//   kSubpixelTextFlag
//   kDevKernTextFlag

paint.setFlags(paint.kAntiAliasFlag | paint.kFilterBitmapFlag);

SkPaint#getStrokeWidth()

Return the current stroke width.

SkPaint#setStrokeWidth(width)

Set the current stroke width to the floating point value width. A width of 0 causes Skia to draw in a special 'hairline' stroking mode.

SkPaint#getStyle()

Return the current style.

SkPaint#setStyle(style)

Set the paint style, for example whether to stroke, fill, or both.

// The follow styles are supported:
//   kFillStyle
//   kStrokeStyle
//   kStrokeAndFillStyle

paint.setStyle(paint.kStrokeStyle);

SkPaint#getStrokeCap

Return the current stroke cap.

SkPaint#setStrokeCap

Set the stroke cap.

// The follow caps are supported:
//   kButtCap
//   kRoundCap
//   kSquareCap
//   kDefaultCap

paint.setStrokeCape(paint.kRoundCap);

SkPaint#setColor(r, g, b, a)

Set the paint color, values are integers in the range of 0 to 255.

SkPaint#setColorHSV(h, s, v, a)

Set the paint color from HSV values, the HSV values are floating point, hue from 0 to 360, and saturation and value from 0 to 1. The alpha value is an integer in the range of 0 to 255.

SkPaint#setTextSize(size)

Set the text size.

SkPaint#setXfermodeMode(mode)

Set the alpha blending (porter duff transfer) mode.

// The following blending modes are supported:
//   kClearMode
//   kSrcMode
//   kDstMode
//   kSrcOverMode
//   kDstOverMode
//   kSrcInMode
//   kDstInMode
//   kSrcOutMode
//   kDstOutMode
//   kSrcATopMode
//   kDstATopMode
//   kXorMode
//   kPlusMode
//   kMultiplyMode
//   kScreenMode
//   kOverlayMode
//   kDarkenMode
//   kLightenMode
//   kColorDodgeMode
//   kColorBurnMode
//   kHardLightMode
//   kSoftLightMode
//   kDifferenceMode
//   kExclusionMode

paint.setXfermodeMode(paint.kPlusMode);  // Additive blending.

SkPaint#setFontFamily(family)

Set the text font family.

SkPaint#setLinearGradientShader

SkPaint#setRadialGradientShader

SkPaint#clearShader

SkPath#reset()

Reset the path to an empty path.

SkPath#rewind()

Reset the path to an empty path, but keeping the internal memory previously allocated for the point storage.

SkPath#moveTo(x, y)

Move to (x, y).

SkPath#lineTo(x, y)

Line to (x, y).

SkPath#rLineTo(rx, ry)

Similar to lineTo(), except rx and ry are relative to the previous point.

SkPath#quadTo(cx, cy, ex, ey)

A quadratic bezier curve with control point (cx, cy) and endpoint (ex, ey).

SkPath#cubicTo(c0x, c0y, c1x, c1y, ex, ey)

A cubic bezier curve with control points (c0x, c0y) and (c1x, c1y) and endpoint (ex, ey).

SkPath#close()

Close the path, connecting the path to the beginning.

SkPath#offset(x, y)

Offset the path by (x, y).

SkPath#getBounds()

Returns an array of [left, top, right, bottom], the bounding rectangle of the path.

SkPath#toSVGString()

Return a string of the path in a format suitable for use in SVG.

var plask = require('plask');
var path = new plask.SkPath();
path.moveTo(10, 20);
path.lineTo(300, 200);
path.toSVGString();  // Returns 'M10 20L300 200'

Math

Plask contains some foundational classes for vector and matrix math.

Constants

kPI   -> Pi
kPI2  -> Pi/2
kPI4  -> Pi/4
k2PI  -> 2*Pi

plask.min(a, b)

Return a or b, whichever is smallest.

plask.max(a, b)

Return a or b, whichever is largest.

plask.clamp(value, vmin, vmax)

Return value if it is between vmin or vmax, otherwise return vmin if value is smaller than vmin, or vmax is value is larger than vmax.

plask.lerp(a, b, t)

Return the interpolation of the values a and b for a given position t. When t is 0, a is returned. When t is 1, b is returned. The interpolation along a and b is returned for any other value of t.

Vec3#add(vec)

Set the vector to the result of the vector plus vec.

Vec3#add2(vec1, vec2)

Set the vector to the result of vec1 plus vec2.

Vec3#added(vec)

Return a new vector, the result of the vector plus vec. This is equivalent to dup().add(vec).

Vec3#cross(vec)

Set the vector to the result of the cross product with vec.

Vec3#cross2(vec1, vec2)

Set the vector to the result of the cross product of vec1 with vec2.

Vec3#debugString()

Return the vector as a formatted string.

Vec3#dot(vec)

Return the result of the dot product with vec.

Vec3#dup()

Return a copy (a new object) of the vector.

Vec3#length()

Return the length (magnitude) of the vector.

Vec3#lengthSquared()

Return the square of the length (magnitude) of the vector.

Vec3#lerp(vec, t)

Set the vector to the interpolation between the vector and vec at t.

Vec3#lerped(vec, t)

Return a new vector, the result of the interpolation between the vector and vec at t.

Vec3#mul(vec)

Set the vector to the result of the vector multiplied by vec.

Vec3#mul2(vec1, vec2)

Set the vector to the result of vec1 multiplied by vec2.

Vec3#mulled(vec)

Return a new vector, the result of the vector multiplied by vec.

Vec3#normalize()

Set the vector to the normalized (length 1) unit vector. It is incorrect to normalize() a vector of zero length.

Vec3#normalized()

Return a new vector, the normalized (length 1) unit vector. It is incorrect to call normalized() on a vector of zero length.

Vec3#scale(s)

Set the vector to the result of multiplying each component by s.

Vec3#scaled(s)

Return a new vector, the result of multiplying each component by s.

Vec3#set(x, y, z)

Set the vector to the components x, y, and z.

Vec3#setVec3(vec)

Set the vector to the components of vec.

Vec3#sub(vec)

Set the vector to the result of the vector minus vec.

Vec3#sub2(vec1, vec2)

Set the vector to the result of vec1 minus vec2.

Vec3#subbed(vec)

Return a new vector, the result of the vector minus vec. This is equivalent to dup().sub(vec).

Mat4#debugString()

Return the matrix as a multi-line formatted string.

Mat4#dup()

Return a copy of the matrix.

Mat4#frustum(l, r, b, t, n, f)

Multiply the matrix by the frustum computed from the left l, right r, bottom b, top t, near n, and far f clipping planes.

Mat4#invert()

Set the matrix to its inverse. The matrix must be invertible.

Mat4#lookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz)

Multiply the matrix by look at matrix computed from the 3 coordinates of the eye position (ex,ey,ez), the center position (cx, cy, cz), and the up vector (ux, uy, uz).

Mat4#mul(mat)

Set the matrix to the result of multiplying by another matrix mat.

Mat4#mul2(mat1, mat2)

Set the matrix to the result of multiplying mat1 by mat2.

Mat4#mul4x4r(...)

Set the matrix to the result of multiplying by a matrix, specified as the 16 matrix values in row major order.

Mat4#mulVec3(v)

Return a new Vec3, the result of multiplying the matrix by v.

Mat4#mulVec4(v)

Return a new Vec4, the result of multiplying the matrix by v.

Mat4#ortho(l, r, b, t, n, f)

Set the matrix to the result of multiplying by the orthographic matrix computed from the left l, right r, bottom b, top t, near n, and far f clipping planes.

Mat4#perspective(fovy, aspect, znear, zfar)

Set the matrix to the result of multiplying by the perspective matrix computed from the field of view fovy, the aspect ratio aspect, and the near znear and far zfar clipping planes.

Mat4#reset()

Set the matrix to the identity.

Mat4#rotate(theta, x, y, z)

Set the matrix to the result of multiplying by the rotation matrix of theta radians about the vector (x, y, z).

Mat4#scale(sx, sy, sz)

Set the matrix to the result of multiplying by the scaling matrix of sx, sy, and sz.

Mat4#set4x4r(...)

Set the matrix to the 16 components specified in row major order.

Mat4#toFloat32Array()

Return a Float32Array of the matrix components, in OpenGL ordering.

Mat4#translate(dx, dy, dz)

Set the matrix to the result of multiplying by the translation matrix of dx, dy, and dz.

Mat4#transpose()

Transpose the matrix (in place).

MIDI

Plask supports sending and receiving MIDI, to both physical and virtual devices.

MidiIn

Create a MIDI input, either virtual or connected to a MIDI source.

var midi = new plask.MidiIn()
var sources = midi.sources();
console.log(sources);
midi.openSource(0);  // Connect to the first MIDI source.
midi.on('noteOn', function(e) {
  console.log(e);  // MIDI note with chan, note, and vel properties.
});

MidiIn#createVirtual(name)

Create a virtual MIDI destination named name. Other applications on the system should be able to see the device under this name and send MIDI to it.

MidiIn#openSource(index)

Attach this MidiIn object to the MIDI source specified by index.

MidiIn#sources

Return an array of the names of MIDI sources. The index of these sources in the array are what should be passed to openSource().

MidiOut

Create a MIDI output, either virtual or connted to a MIDI destination.

var midi = new plask.MidiOut();
var destinations = midi.destinations();
console.log(destinations);
midi.openDestination(0);  // Connect to the first MIDI destination.
midi.noteOn(1, 30, 127);  // Send note 30 on channel 1 at full velocity.

MidiOut#controller(chan, con, val)

Send a MIDI controller message on channel chan, controller number con, and a 7-bit integer value val.

MidiOut#createVirtual(name)

Create a virtual MIDI source named name. Other applications on the system should be able to see the deice under this name and receive MIDI from it.

MidiOut#destinations()

Return an array of the names of the available MIDI destinations on the system. The index of this array should be passed to openDestination().

MidiOut#noteOff(chan, note, vel)

Send a MIDI note off message, on channel chan, for note note, of a velocity vel.

MidiOut#noteOn(chan, note, vel)

Send a MIDI note on message, on channel chan, for note note, of a velocity vel.

MidiOut#openDestination(index)

Attach this MidiOut object to the destination specific by index.

MidiOut#pitchWheel(chan, val)

Send a MIDI pitch wheel message on channel chan, with a value (range -1 .. 1) of val. The floating point val will be mapped to the 14-bit MIDI integer.