vsketch.Vsketch

class Vsketch

This class implement the core vsketch API.

All drawing are created through an instance of Vsketch.

Methods

__init__

Initialize self.

arc

Draw an arc.

bezier

Draws a Bezier curve

bezierPoint

Evaluates the Bezier at point t for points a, b, c, d.

bezierTangent

Calculates the tangent of a point on a Bezier curve.

circle

Draw a circle.

detail

Define the level of detail for curved paths.

display

Display the sketch on screen.

ellipse

Draw an ellipse.

ellipseMode

Change the way parameters are interpreted to draw ellipses.

fill

Set the current fill color.

geometry

Draw a Shapely geometry.

lerp

Interpolate between two numbers or arrays.

line

Draw a line.

map

Re-map a value from one range to the other.

noFill

Disable fill.

noStroke

Disable stroke.

noise

Returns the Perlin noise value at specified coordinates.

noiseDetail

Adjusts parameters of the Perlin noise function.

noiseSeed

Set the random seed for noise().

penWidth

Configure the pen width.

point

Draw a point.

polygon

Draw a polygon.

popMatrix

Pop the current transformation matrix from the matrix stack.

printMatrix

Print the current transformation matrix.

pushMatrix

Push the current transformation matrix onto the matrix stack.

quad

Draw a quadrilateral.

random

Return a random number with an uniform distribution between specified bounds.

randomGaussian

Return a random number according to a gaussian distribution with a mean of 0 and a standard deviation of 1.0.

randomSeed

Set the seed for random() and randomGaussian().

rect

Draw a rectangle.

rectMode

Change the way parameters are interpreted to draw rectangles.

resetMatrix

Reset the current transformation matrix.

rotate

Apply a rotation to the current transformation matrix.

save

Save the current sketch to a SVG or HPGL file.

scale

Apply a scale factor to the current transformation matrix.

size

Define the page layout.

sketch

Draw the content of another Vsketch.

square

Draw a square.

stroke

Set the current stroke color.

strokeJoin

Set the style of the joints that connects line segments.

strokeWeight

Set the stroke weight.

translate

Apply a translation to the current transformation matrix.

triangle

Draw a triangle.

vpype

Execute a vpype pipeline on the current sketch.

Attributes

centered

Controls whether the sketch should be centered on page.

document

Return the vpype.Document instance containing the sketch’s geometries.

epsilon

Returns the segment maximum length for curve approximation.

fillPenWidth

Returns the pen width to be used for fill, or None in noFill() mode.

height

Get the page height in CSS pixels.

strokePenWidth

Returns the pen width to be used for stroke, or 0 in noStroke() mode.

transform

Get the current transform matrix.

width

Get the page width in CSS pixels.

Methods

Vsketch.__init__()

Initialize self. See help(type(self)) for accurate signature.

Vsketch.arc(x, y, w, h, start, stop, degrees=False, close='no', mode=None)

Draw an arc.

The way x, y, w, and h parameters are interpreted depends on the current ellipse mode (see ellipse() for a detailed explanation) and refer to the arc’s underlying ellipse.

The close parameter controls the arc’s closure: no keeps it open, chord closes it with a straight line, and pie connects the two endings with the arc center.

Example

>>> vsk = Vsketch()
>>> vsk.arc(2, 3, 5, 4, 0, np.pi / 2)
>>> vsk.arc(6, 6, 1, 2, np.pi / 2, np.pi, mode="corner", close="pie")
Parameters
  • x (float) -- by default, X coordinate of the associated ellipse center

  • y (float) -- by default, Y coordinate of the associated ellipse center

  • w (float) -- by default, width of the associated ellipse

  • h (float) -- by default, height of the associated ellipse

  • start (float) -- angle to start the arc (in radians)

  • stop (float) -- angle to stop the arc (in radians)

  • degrees (Optional[bool]) -- set to True to use degrees for start and stop angles (default: False)

  • close (Optional[str]) -- “no”, “chord” or “pie” (default: “no”)

  • mode (Optional[str]) -- “corner”, “corners”, “radius”, or “center” (see ellipseMode())

Return type

None

Vsketch.bezier(x1, y1, x2, y2, x3, y3, x4, y4)

Draws a Bezier curve

Bezier curves are defined by a series of anchor and control points. The first two arguments specify the first anchor point and the last two arguments specify the other anchor point. The middle arguments specify the control points which define the shape of the curve.

Parameters
  • x1 (float) -- X coordinate of the first anchor point

  • y1 (float) -- Y coordinate of the first anchor point

  • x2 (float) -- X coordinate of the first control point

  • y2 (float) -- Y coordinate of the first control point

  • x3 (float) -- X coordinate of the second control point

  • y3 (float) -- Y coordinate of the second control point

  • x4 (float) -- X coordinate of the second anchor point

  • y4 (float) -- Y coordinate of the second anchor point

Return type

None

Vsketch.bezierPoint(a, b, c, d, t)

Evaluates the Bezier at point t for points a, b, c, d. The parameter t varies between 0 and 1, a and d are points on the curve, and b and c are the control points. This can be done once with the X coordinates and a second time with the Y coordinates to get the location of a bezier curve at t.

See also

bezier()

Parameters
  • a (float) -- coordinate of the first point of the curve

  • b (float) -- coordinate of the first control point

  • c (float) -- coordinate of the second control point

  • d (float) -- coordinate of the second point of the curve

  • t (float) -- value between 0 and 1

Return type

float

Returns

evaluated coordinate on the bezier curve

Vsketch.bezierTangent(a, b, c, d, t)

Calculates the tangent of a point on a Bezier curve.

Parameters
  • a (float) -- coordinate of the first point of the curve

  • b (float) -- coordinate of the first control point

  • c (float) -- coordinate of the second control point

  • d (float) -- coordinate of the second point of the curve

  • t (float) -- value between 0 and 1

Return type

float

Returns

evaluated tangent on the bezier curve

Vsketch.circle(x, y, diameter=None, radius=None, mode=None)

Draw a circle.

The level of detail used to approximate the circle is controlled by detail(). As for the ellipse() function, the way arguments are interpreted is influenced by the mode set with ellipseMode() or the mode argument.

Example

>>> vsk = Vsketch()
>>> vsk.circle(0, 0, 10)  # by default, diameter is used
>>> vsk.circle(0, 0, radius=5)  # radius can be specified instead
Parameters
  • x (float) -- x coordinate of the center

  • y (float) -- y coordinate of the center

  • diameter (Optional[float]) -- circle diameter (or None if using radius)

  • radius (Optional[float]) -- circle radius (or None if using diameter

  • mode (Optional[str]) -- one of ‘center’, ‘radius’, ‘corner’, ‘corners’

Return type

None

Vsketch.detail(epsilon)

Define the level of detail for curved paths.

Vsketch internally stores exclusively so called line strings, i.e. paths made of straight segments. Curved geometries (e.g. circle()) are approximated by many small segments. The level of detail controls the maximum size these segments may have. The default value is set to 0.1mm, with is good enough for most plotting needs.

Note: detail() applies to all primitives, including e.g. bezier(). As such, it replaces some of Processing’s API, such as bezierDetail() or curveDetail().

Examples:

:func:`detail` accepts string values with unit::

    >>> vsk = Vsketch()
    >>> vsk.detail("1mm")

A float input is interpretted as CSS pixels::

    >>> vsk.detail(1.)
Parameters

epsilon (Union[float, str]) -- maximum length of segments approximating curved elements (may be a string value with units -- float value are interpreted as CSS pixels

Return type

None

Vsketch.display(mode=None, paper=True, pen_up=False, color_mode='layer', axes=False, grid=False, unit='px', fig_size=None)

Display the sketch on screen.

This function displays the sketch on screen using the most appropriate mode depending on the environment.

In standalone mode (vsketch used as a library), "matplotlib" mode is used by default. Otherwise (i.e. in Jupyter Lab or Google Colab), "ipython" mode is used instead.

The default options are the following:

  • The sketch is laid out on the desired page size, the boundary of which are displayed.

  • The path are colored layer by layer.

  • Pen-up trajectories are not displayed.

  • Advanced plotting options (axes, grid, custom units) are disabled.

All of the above can be controlled using the optional arguments.

Examples

In most case, the default behaviour is best:

>>> vsk = Vsketch()
>>> # draw stuff...
>>> vsk.display()

Sometimes, seeing the page boundaries and a laid out sketch is not useful:

>>> vsk.display(paper=False)

The "matplotlib" mode has additional options that can occasionaly be useful:

>>> vsk.display(mode="matplotlib", axes=True, grid=True, unit="cm")
Parameters
  • mode ("matplotlib" or "ipython") -- override the default display mode

  • paper (bool) -- if True, the sketch is laid out on the desired page size (default: True)

  • pen_up (bool) -- if True, the pen-up trajectories will be displayed (default: False)

  • color_mode ("none", "layer", or "path") -- controls how color is used for display ("none": black and white, "layer": one color per layer, "path": one color per path — default: "layer")

  • axes (bool) -- ("matplotlib" only) if True, labelled axes are displayed (default: False)

  • grid (bool) -- ("matplotlib" only) if True, a grid is displayed (default: False)

  • unit (str) -- ("matplotlib" only) use a specific unit for the axes (default: “px”)

  • fig_size (Optional[Tuple[float, float]]) -- ("matplotlib" only) specify the figure size

Return type

None

Vsketch.ellipse(x, y, w, h, mode=None)

Draw an ellipse.

The way x, y, w, and h parameters are interpreted depends on the current ellipse mode.

By default, x and y set the location of the ellipse center, w sets its width, and h sets its height. The way these parameters are interpreted can be changed with the ellipseMode() function (which changes the default for subsequent calls to ellipse()) or the mode argument (which only affects this call).

Examples

By default, the argument are interpreted as the center coordinates as well as the width and height:

>>> vsk = Vsketch()
>>> vsk.ellipse(2, 2, 1, 4)

Alternative ellipse mode can be set as the default for subsequence calls with ellipseMode():

>>> vsk.ellipseMode(mode="radius")
>>> vsk.ellipse(3, 3, 2, 1)
>>> vsk.ellipse(8, 8, 2, 1)  # both of these call are in "radius" mode

Or they can be set for a single call only:

>>> vsk.ellipse(2, 2, 10, 12, mode="corners")
Parameters
  • x (float) -- by default, x coordinate of the ellipse center

  • y (float) -- by default, y coordinate of the ellipse center

  • w (float) -- by default, the ellipse width

  • h (float) -- by default, the ellipse height

  • mode (Optional[str]) -- “corner”, “corners”, “radius”, or “center” (see ellipseMode())

Return type

None

Vsketch.ellipseMode(mode)

Change the way parameters are interpreted to draw ellipses.

The default is “center”, where the first two parameters are the center coordinates, and the third and fourth are the width and height of the ellipse.

“radius” interprets the first two parameters as the center coordinates, while the third and fourth represent half the width and height of the ellipse.

“corner” interprets the first two parameters as the top-left corner coordinates of the ellipse’s bounding box, while the third and fourth parameters are the ellipse width and height.

“corners” interprets the first two parameters as the coordinates of a corner of the ellipse’s bounding box, and the third and fourth parameters as the opposite corner coordinates.

See also

Example

>>> vsk = Vsketch()
>>> vsk.ellipseMode("radius")
>>> vsk.ellipse(2, 2, 3, 5)
Parameters

mode (str) -- one of “center”, “radius”, “corner”, “corners”.

Return type

None

Vsketch.fill(c)

Set the current fill color. :type c: int :param c: the color (e.g. layer) to use for fill :type c: strictly positive int

Return type

None

Vsketch.geometry(shape)

Draw a Shapely geometry.

This function should accept any of LineString, LinearRing, MultiPoint, MultiPolygon, MultiLineString, Point, or Polygon.

Parameters

shape (Shapely geometry) -- a supported shapely geometry object

Return type

None

static Vsketch.lerp(start, stop, amt)

Interpolate between two numbers or arrays.

The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc.

Examples:

>>> vsk = Vsketch()
>>> vsk.lerp(0., 10, 0.3)
3.
>>> vsk.lerp(np.array([0, 1, 2]), np.array(10, 11, 12), 0.5)
array([5., 6., 7.])
Parameters
Return type

Union[float, complex, ndarray]

Returns

interpolated value or array

Vsketch.line(x1, y1, x2, y2)

Draw a line.

Parameters
  • x1 (float) -- X coordinate of starting point

  • y1 (float) -- Y coordinate of starting point

  • x2 (float) -- X coordinate of ending point

  • y2 (float) -- Y coordinate of ending point

Return type

None

static Vsketch.map(value, start1, stop1, start2, stop2)

Re-map a value from one range to the other.

Input values are not clamped. This function accept float or NumPy array, in which case it also returns a Numpy array.

Examples:

>>> vsk = Vsketch()
>>> vsk.map(5, 0, 10, 40, 60)
50
>>> vsk.map(-1, 0, 1, 0, 30)
-30
>>> vsk.map(np.arange(5), 0, 5, 10, 30)
array([10., 14., 18., 22., 26.])
Parameters
  • value (Union[float, ndarray]) -- value or array of value to re-map

  • start1 (float) -- low bound of the value’s current range

  • stop1 (float) -- high bound of the value’s current range

  • start2 (float) -- low bound of the target range

  • stop2 (float) -- high bound of the target range

Return type

Union[float, ndarray]

Returns

the re-maped value or array

Vsketch.noFill()

Disable fill.

Return type

None

Vsketch.noStroke()

Disable stroke.

Return type

None

Vsketch.noise(x: numbers.Number, y: Optional[numbers.Number] = None, z: Optional[numbers.Number] = None, grid_mode: bool = True)float
Vsketch.noise(x: Union[Sequence[float], numpy.ndarray], y: Union[None, numbers.Number, Sequence[float], numpy.ndarray] = None, z: Union[None, numbers.Number, Sequence[float], numpy.ndarray] = None, grid_mode: bool = True)numpy.ndarray

Returns the Perlin noise value at specified coordinates.

This function sample 1D, 2D or 3D noise space, depending on the number of coordinates provided. The coordinates may be either scalar values or vectors. In the later case, noise() can operate in grid mode (default) or not.

When x, y, and z are scalar values, this function returns a float value:

>>> vsk = Vsketch()
>>> vsk.noise(1.0, 1.0, 1.0)
0.5713948646260701

With grid mode enabled, either or all of x, y, and z can also be 1D vectors (any sequence type, such as Numpy array), each with possibly different length. noise() computes values for every combination of the input parameters:

>>> vsk.noise([0, 0.1, 0.2, 0.3, 0.4])
array([0.73779253, 0.7397108 , 0.73590816, 0.72425246, 0.69773313])
>>> vsk.noise([0., 1.], np.linspace(0., 1., 5))
array([[0.73779253, 0.61588815, 0.52075717, 0.48219902, 0.50484146],
       [0.59085755, 0.67609827, 0.73308901, 0.74057962, 0.75528381]])
>>> vsk.noise(np.linspace(0., 1., 100), np.linspace(0., 1., 50), [0, 100]).shape
(100, 50, 2)

With grid mode disabled, the provided input coordinates must all have the same shape and the returned array will also have this shape. In this example, the Perlin 2D noise field is sample along the diagonal:

>>> vsk.noise(np.linspace(0, 1, 10), np.linspace(0, 1, 10), grid_mode=False)
array([0.57731468, 0.58830833, 0.61182686, 0.59998289, 0.64938922,
0.68599367, 0.62879284, 0.6615939 , 0.73334911, 0.76806402])

The vectorised version of noise() is several orders of magnitude faster than the corresponding scalar calls. It is thus strongly recommended to use few, out-of-loop, vectorized calls instead of many in-loop scalar calls.

For a given Vsketch instance, a given coordinate will always yield the same pseudo-random value, unless another seed is set (noiseSeed()).

See Processing’s description of Perlin noise for background information.

Parameters
  • x -- X coordinate in the noise space

  • y -- Y coordinate in the noise space (if provided)

  • z -- Z coordinate in the noise space (if provided)

  • grid_mode -- enable grid mode (default: True)

Returns

noise value between 0.0 and 1.0

Vsketch.noiseDetail(lod, falloff=None)

Adjusts parameters of the Perlin noise function.

By default, noise is computed over 4 octaves with each octave contributing exactly half of it s predecessors. This falloff as well as the number of octaves can be adjusted with this function

See also

Parameters
  • lod (int) -- number of octaves to use

  • falloff (Optional[float]) -- ratio of amplitude of one octave with respect to the previous one

Return type

None

Vsketch.noiseSeed(seed)

Set the random seed for noise().

See also

noise()

Parameters

seed (int) -- the seed

Return type

None

Vsketch.penWidth(width, layer=None)

Configure the pen width.

For some feature, vsketch needs to know the width of your pen to for an optimal output. For example, the hatching pattern generated by fill() must be spaced by the right amount. The default pen width is set to 0.3mm.

The default pen width can be set this way, and will be used for all layers unless a layer-specific pen width is provided:

>>> vsk = Vsketch()
>>> vsk.penWidth("0.5mm")

A layer-specific pen width can be defined this way:

>>> vsk.penWidth("1mm", 2)  # set pen width of layer 2 to 1mm

If float is used as input, it is interpreted as CSS pixels.

Parameters
  • width (Union[float, str]) -- pen width

  • layer (Optional[int]) -- if provided, ID of the layer for which the pen width must be set (otherwise the default pen width is changed)

Return type

None

Vsketch.point(x, y)

Draw a point.

For best plotting results, a tiny circle is actually drawn with diameter set to the current layer’s pen width.

Example:

>>> vsk = Vsketch()
>>> vsk.point(2, 3.5)
Parameters
  • x (float) -- X coordinate

  • y (float) -- Y coordinate

Return type

None

Vsketch.polygon(x, y=None, holes=(), close=False)

Draw a polygon.

Examples

A single iterable of size-2 sequence can be used:

>>> vsk = Vsketch()
>>> vsk.polygon([(0, 0), (2, 3), (3, 2)])

A 1-dimension iterable of complex can also be used:

>>> vsk.polygon([3 + 3j, 2 + 5j, 4 + 7j])

Alternatively, two iterables of float can be passed:

>>> vsk.polygon([0, 2, 3], [0, 3, 2])

The polygon can be automatically closed if needed:

>>> vsk.polygon([0, 2, 3], [0, 3, 2], close=True)

Finally, polygons can have holes, which is useful when using fill():

>>> vsk.polygon([0, 1, 1, 0], [0, 0, 1, 1],
...             holes=[[(0.3, 0.3), (0.3, 0.6), (0.6, 0.6)]])
Parameters
Return type

None

Vsketch.popMatrix()

Pop the current transformation matrix from the matrix stack.

Return type

None

Vsketch.printMatrix()

Print the current transformation matrix.

Return type

None

Vsketch.pushMatrix()

Push the current transformation matrix onto the matrix stack.

Each call to pushMatrix() should be matched by exactly one call to popMatrix() to maintain consistency. Alternatively, the context manager returned by pushMatrix() can be used to automatically call popMatrix()

Examples

Using matching popMatrix():

>>> vsk = Vsketch()
>>> for _ in range(5):
...    vsk.pushMatrix()
...    vsk.rotate(_*5, degrees=True)
...    vsk.rect(-2, -2, 2, 2)
...    vsk.popMatrix()
...    vsk.translate(5, 0)
...

Using context manager:

>>> for _ in range(5):
...    with vsk.pushMatrix():
...        vsk.rotate(_*5, degrees=True)
...        vsk.rect(-2, -2, 2, 2)
...    vsk.translate(5, 0)
...
Returns

a context manager object for use with a with statement

Return type

context manager object

Vsketch.quad(x1, y1, x2, y2, x3, y3, x4, y4)

Draw a quadrilateral.

Example

>>> vsk = Vsketch()
>>> vsk.quad(0, 0, 1, 3.5, 4.5, 4.5, 3.5, 1)
Parameters
  • x1 (float) -- X coordinate of the first vertex

  • y1 (float) -- Y coordinate of the first vertex

  • x2 (float) -- X coordinate of the second vertex

  • y2 (float) -- Y coordinate of the second vertex

  • x3 (float) -- X coordinate of the third vertex

  • y3 (float) -- Y coordinate of the third vertex

  • x4 (float) -- X coordinate of the last vertex

  • y4 (float) -- Y coordinate of the last vertex

Return type

None

Vsketch.random(a, b=None)

Return a random number with an uniform distribution between specified bounds.

Examples

When using a single argument, it is used as higher bound and 0 is the lower bound:

>>> vsk = Vsketch()
>>> vsk.random(10)
5.887767258845811

When using both arguments, they are used as lower and higher bounds:

>>> vsk.random(30, 40)
37.12222388435382
Parameters
  • a (float) -- if b is provided: low bound, otherwise: high bound

  • b (Optional[float]) -- high bound

Return type

float

Returns

the random value

Vsketch.randomGaussian()

Return a random number according to a gaussian distribution with a mean of 0 and a standard deviation of 1.0.

Return type

float

Returns

the random value

Vsketch.randomSeed(seed)

Set the seed for random() and randomGaussian().

By default, Vsketch instance are initialized with a random seed. By explicitly setting the seed, the sequence of number returned by random() and randomGaussian() will be reproduced predictably.

Note that each Vsketch instance has it’s own random state and will not affect other instances.

Parameters

seed (int) -- the seed to use

Return type

None

Vsketch.rect(x, y, w, h, *radii, tl=None, tr=None, br=None, bl=None, mode=None)

Draw a rectangle.

The way x, y, w, and h parameters are interpreted depends on the current rect

By default, x and y set the location of the upper-left corner, w sets the width, and h sets the height. The way these parameters are interpreted can be changed with the rectMode() function (which changes the default for subsequent calls to rect()) or the mode argument (which only affects this call).

The optional parameters tl, tr, br and bl define the radius used for each corner (default: 0). If some corner radius is not specified, it will be set equal to the previous corner radius. If the sum of two consecutive corner radii are greater than their associated edge lenght, their values will be rescaled to fit the rectangle.

Examples

By default, the argument are interpreted as the top left corner as well as the width and height:

>>> vsk = Vsketch()
>>> vsk.rect(0, 0, 2, 4)  # 2x4 rectangle with top-left corner at (0, 0)

Alternative rect mode can be set as the default for subsequence calls with rectMode():

>>> vsk.rectMode(mode="radius")
>>> vsk.rect(3, 3, 2, 1)
>>> vsk.rect(8, 8, 2, 1)  # both of these call are in "radius" mode

Or they can be set for a single call only:

>>> vsk.rect(2, 2, 10, 12, mode="corners")

Drawing rectangles with rounded corners:

>>> vsk.rect(0, 0, 5, 5, 5)  # all corners are rounded with a radius of 5
>>> vsk.rect(0, 0, 4, 4, 1.5, 0.5, 1.5, 1)  # all corner radii specified
>>> vsk.rect(5, 5, 20, 20, tr=3, bl=5)  # specified corners rounded, others
                                        # default to 0
Parameters
  • x (float) -- by default, x coordinate of the top-left corner

  • y (float) -- by default, y coordinate of the top-left corner

  • w (float) -- by default, the rectangle width

  • h (float) -- by default, the rectangle height (same as width if not provided)

  • tl (Optional[float]) -- top-left corner radius (0 if not provided)

  • tr (Optional[float]) -- top-right corner radius (same as tl if not provided)

  • br (Optional[float]) -- bottom-right corner radius (same as tr if not provided)

  • bl (Optional[float]) -- bottom-left corner radius (same as br if not provided)

  • mode (Optional[str]) -- “corner”, “corners”, “redius”, or “center” (see rectMode())

Return type

None

Vsketch.rectMode(mode)

Change the way parameters are interpreted to draw rectangles.

The default is “corner”, where the first two parameters are the top-left corner coordinates, and the third and fourth are the width, respectively the height of the rectangle.

In rect(), “corners” interprets the first two parameters as the coordinates of a corner, and the third and fourth parameters as the opposite corner coordinates. In square(), “corners” is interpreted as “corner”.

“center” interprets the first two parameters as the shape’s center coordinates, and the third and fourth parameters as the shape’s width and height.

“radius” interprets the first two parameters as the shape’s center coordinates, and the third and fourth parameters as half of the shape’s width and height.

See also

Example

>>> vsk = Vsketch()
>>> vsk.rectMode("center")
>>> vsk.square(3, 3, 1.5)
>>> vsk.rect(2, 2, 3.5, 1)
Parameters

mode (str) -- one of “corner”, “corners”, “center”, “radius”.

Return type

None

Vsketch.resetMatrix()

Reset the current transformation matrix.

It can also be used as a context manager. In this case, pushMatrix() and its associated popMatrix() will be called automatically.

Examples

Using resetMatrix() as is:

>>> vsk = Vsketch()
>>> vsk.rotate(45)
>>> vsk.scale(20, 3)
>>> vsk.rect(0, 0, 4, 5)  # will be rotated and scaled
>>> vsk.resetMatrix()
>>> vsk.rect(0, 0, 2, 3)  # won't be rotated and scaled

Using context manager:

>>> vsk = Vsketch()
>>> vsk.rotate(42)
>>> with vsk.resetMatrix():
...     vsk.rect(5, 4, 20, 15)  # won't be rotated by 42° rotation
>>> vsk.rect(2, 2, 10, 10)  # will be rotated by 42°

See also

Returns

a context manager object for use with a with statement

Return type

context manager object

Vsketch.rotate(angle, degrees=False)

Apply a rotation to the current transformation matrix.

The coordinates are always rotated around their relative position to the origin. Positive numbers rotate objects in a clockwise direction and negative numbers rotate in the counter-clockwise direction.

Parameters
  • angle (float) -- the angle of the rotation in radian (or degrees if degrees=True)

  • degrees (bool) -- if True, the input is interpreted as degree instead of radians

Return type

None

Vsketch.save(file, device=None, *, format=None, color_mode='layer', layer_label='%d', paper_size=None, velocity=None, quiet=False)

Save the current sketch to a SVG or HPGL file.

file may either be a file path or a IO stream handle (such as the one returned by Python’s open() built-in).

This function uses the page layout as defined by size().

Due to the nature of HPGL (which much be generated for a specific plotter device/paper size combination), the device name must always be specified. If paper_size is not provided, save() attempts to infer which paper configuration to use based on the page size provided to size(). If multiple configurations match the page size, the first one is used. In case of ambiguity, it is recommendande to specify paper_size. See vpype’s documentation for more information on HPGL generation.

Examples

Save the sketch to a SVG file:

>>> vsk = Vsketch()
>>> vsk.size("a4", landscape=True)
>>> # draw stuff...
>>> vsk.save("output.svg")

Save to a SVG file with customization:

>>> vsk.save("output.svg", color_mode="path", layer_label="layer %d")

Save to a HPGL file:

>>> vsk.save("output.hpgl", "hp7475a")

Save to a HPGL file with customization:

>>> vsk.save("output.hpgl", "hp7475a", paper_size="a4", veolocty=30)
Parameters
  • file (Union[str, TextIO]) -- destination SVG file (can be a file path or text-based IO stream)

  • device (Optional[str]) -- (HPGL only) target device for the HPGL output

  • format ("svg", "hpgl") -- specify the format of the output file (default is inferred from the file extension)

  • color_mode ("none", "layer", or "path") -- (SVG only) controls how color is used for display ("none": black and white, "layer": one color per layer, "path": one color per path — default: "layer")

  • layer_label (str) -- (SVG only) define a template for layer naming (use %d for layer ID)

  • paper_size (Optional[str]) -- (HPGL only) name of the paper size to use, as configured for the specified device (if omitted, the paper size will be inferred based on the page size specified with size())

  • velocity (Optional[float]) -- (HPGL only) if provided, a VS command will be emitted with the provided velocity

  • quiet (bool) -- (HPGL only) if set to True, silence plotter configuration and paper loading instructions

Return type

None

Vsketch.scale(sx, sy=None)

Apply a scale factor to the current transformation matrix.

Examples

Set sketch units to centimeters:

>>> vsk = Vsketch()
>>> vsk.scale("1cm")
>>> vsk.square(5, 5, 2)  # square with 2cm-long sides

Apply a non-homogeneous scale transformation:

>>> vsk.scale(2, 3)
Parameters
  • sx (Union[float, str]) -- scale factor along x axis (can be a string with units)

  • sy (Union[float, str, None]) -- scale factor along y axis (can be a string with units) or None, in which case the same value as sx is used

Return type

None

Vsketch.size(width, height=None, landscape=False, center=True)

Define the page layout.

If floats are for width and height, they are interpreted as CSS pixel (same as SVG). Alternatively, strings can be passed and may contain units. The string form accepts both two parameters, or a single, vpype-like page size specifier.

Page size specifier can either be a known page size (see vpype write --help for a list) or a string in the form of WxH, where both W and H may have units (e.g. 15inx10in.

By default, the sketch is always centered on the page. This can be disabled with center=False. In this case, the sketch’s absolute coordinates are used, with (0, 0) corresponding to the page’s top-left corener and Y coordinates increasing downwards.

The current page size (in CSS pixels) can be obtained with width and height properties.

Examples

Known page size can be used directly:

>>> vsk = Vsketch()
>>> vsk.size("a4")

Alternatively, the page size can be explicitely provided. All of the following calls are strictly equivalent:

>>> vsk.size("15in", "10in")
>>> vsk.size("10in", "15in", landscape=True)
>>> vsk.size("15inx10in")
>>> vsk.size("15in", 960.)  # 1in = 96 CSS pixels
Parameters
  • width (Union[float, str]) -- page width or page forwat specifier if h is omitted

  • height (Union[float, str, None]) -- page height

  • landscape (bool) -- rotate page size by 90 degrees if True

  • center (bool) -- if False, automatic centering is disabled

Return type

None

Vsketch.sketch(sub_sketch)

Draw the content of another Vsketch.

Vsketch objects being self-contained, multiple instances can be created by a single program, for example to create complex shapes in a sub-sketch to be used multiple times in the main sketch. This function can be used to draw in a sketch the content of another sketch.

The styling options (stroke layer, fill layer, pen width, etc.) must be defined in the sub-sketch and are preserved by sketch(). Layers IDs are preserved and will be created if needed.

The current transformation matrix is applied on the sub-sketch before inclusion in the main sketch.

Parameters

sub_sketch (Vsketch) -- sketch to draw in the current sketch

Return type

None

Vsketch.square(x, y, extent, mode=None)

Draw a square.

As for the rect() function, the way arguments are interpreted is influenced by the mode set with rectMode() or the mode argument.

See also

Example

>>> vsk = Vsketch()
>>> vsk.square(2, 2, 2.5)
Parameters
  • x (float) -- X coordinate of top-left corner

  • y (float) -- Y coordinate of top-left corner

  • extent (float) -- width and height of the square

  • mode (Optional[str]) -- “corner”, “radius”, or “center” (see rectMode()) — note that the “corners” mode is meaningless for this function, and is interpreted as the “corner” mode

Return type

None

Vsketch.stroke(c)

Set the current stroke color.

Parameters

c (strictly positive int) -- the color (e.g. layer) to use for path

Return type

None

Vsketch.strokeJoin(join_style)

Set the style of the joints that connects line segments.

Defines how joints between line segments are drawn when stroke weight is greater than 1. The available styles are "round" (default), "mitre", and "bevel".

Parameters

join_style ("round", "mitre", or "bevel") -- join style to use

Return type

None

Vsketch.strokeWeight(weight)

Set the stroke weight.

By default, stroke are plotted with a single line. Stroke can be made thicker by setting weight greater than 1 using this function. With stroke weight greater than 1, each stroke will be drawn with multiple lines, each spaced by the pen width defined for the current layer. The pen width must thus be properly set for good results.

See also

Parameters

weight (strictly positive int) -- number of plotted lines to use for strokes

Return type

None

Vsketch.translate(dx, dy)

Apply a translation to the current transformation matrix.

Parameters
  • dx (float) -- translation along X axis

  • dy (float) -- translation along Y axis

Return type

None

Vsketch.triangle(x1, y1, x2, y2, x3, y3)

Draw a triangle.

Example

>>> vsk = Vsketch()
>>> vsk.triangle(2, 2, 2, 3, 3, 2.5)
Parameters
  • x1 (float) -- X coordinate of the first corner

  • y1 (float) -- Y coordinate of the first corner

  • x2 (float) -- X coordinate of the second corner

  • y2 (float) -- Y coordinate of the second corner

  • x3 (float) -- X coordinate of the third corner

  • y3 (float) -- Y coordinate of the third corner

Return type

None

Vsketch.vpype(pipeline)

Execute a vpype pipeline on the current sketch.

Calling this function is equivalent to the following pseudo-command:

$ vpype [load from sketch] pipeline [save to sketch]

See vpype’s documentation for more information the commands available.

Notes

  • vpype is unaware of transforms. This means that any coordinates and length passed to vpype is interpreted as if no transform was applied. vpype does understand units though. If you used transforms to work in a different unit than CSS pixel (e.g. vsk.scale("1cm"), then use the same unit with vpype() (e.g. vsk.vpype("crop 1cm 1cm 10cm 10cm").

  • vpype is unaware of the automatic centering mechanism built in size(), display() and save(). The pipeline is applied on the un-centered geometries. In some case, it may be useful to pass center=False to size() to avoid confusion.

  • It is not recommended to use layer manipulation commands (e.g. lmove, ldelete, and lcopy) as this can lead to discrepancies with some of the metadata vsketch maintains, such as the attached pen widths (see penWidth()).

Example

The most common use-case for this function is plot optimization:

>>> import vsketch
>>> vsk = vsketch.Vsketch()
>>> # draw stuff...
>>> vsk.vpype("linesimplify linemerge reloop linesort")
>>> vsk.save("output.svg")

This pipeline does the following:

  • linesimplify: Reduces the number of segment within all paths to the minimum needed to ensure quality. This reduces SVG file size and avoid performance issues while plotting.

  • linemerge: Merge lines whose ends are very close to avoid unnecessary pen-up/pen-down sequences. By default, this command will consider swapping the path direction for merging.

  • reloop: Randomize the location of the seam for closed paths. When many similar paths are used on a plot (say, circles), having the seam at the same location can lead to disturbing artefacts on the final plot, which this command avoids.

  • linesort: Reorder the paths to minimize the pen-up travel distance. By default, this command will consider swapping the path direction for further optimization.

Parameters

pipeline (str) -- vpype pipeline to apply to the sketch

Return type

None

Attributes

Vsketch.centered

Controls whether the sketch should be centered on page.

Return type

bool

Vsketch.document

Return the vpype.Document instance containing the sketch’s geometries.

Vsketch.epsilon

Returns the segment maximum length for curve approximation.

The returned value takes into account the desired level of detail (see detail`() as well as the scaling to be applied by the current transformation matrix.

Return type

float

Returns

the maximum segment length to use

Vsketch.fillPenWidth

Returns the pen width to be used for fill, or None in noFill() mode.

Return type

Optional[float]

Returns

the current fill pen width

Vsketch.height

Get the page height in CSS pixels.

Return type

float

Returns

page height

Vsketch.strokePenWidth

Returns the pen width to be used for stroke, or 0 in noStroke() mode.

Return type

float

Returns

the current stroke pen width

Vsketch.transform

Get the current transform matrix.

Return type

ndarray

Returns

the current 3x3 homogenous planar transform matrix

Vsketch.width

Get the page width in CSS pixels.

Return type

float

Returns

page width