vsketch#
This module implements the vsketch API.
Overview#
Core drawing API. |
|
Reusable and drawable shape with support for boolean operations. |
|
Base class for sketch managed with the |
|
Generic parameter for |
Classes#
- class vsketch.Vsketch#
Core drawing API.
All drawing are created through an instance of
Vsketch
.Typically, a
Vsketch
instance is provided to yourSketchClass
subclass by vsketch.Alternatively,
Vsketch
instance may be manually created and used in a standalone script:>>> import vsketch >>> vsk = vsketch.Vsketch() >>> vsk.rect(10, 10, 50, 50) >>> vsk.display() >>> vsk.save("output.svg")
Overview
Methods# detail
(epsilon)Define the level of detail for curved paths.
size
(width, height, landscape, center)Define the page layout.
stroke
(c)Set the current stroke color.
noStroke
()Disable stroke.
strokeWeight
(weight)Set the stroke weight.
strokeJoin
(join_style)Set the style of the joints that connects line segments.
fill
(c)Set the current fill color.
noFill
()Disable fill.
penWidth
(width, layer)Configure the pen width.
Reset the current transformation matrix.
Push the current transformation matrix onto the matrix stack.
Pop the current transformation matrix from the matrix stack.
Print the current transformation matrix.
scale
(sx, sy)Apply a scale factor to the current transformation matrix.
rotate
(angle, degrees)Apply a rotation to the current transformation matrix.
translate
(dx, dy)Apply a translation to the current transformation matrix.
line
(x1, y1, x2, y2)Draw a line.
circle
(x, y, diameter, radius, mode)Draw a circle.
ellipse
(x, y, w, h, mode)Draw an ellipse.
arc
(x, y, w, h, start, stop, degrees, close, mode)Draw an arc.
ellipseMode
(mode)Change the way parameters are interpreted to draw ellipses.
point
(x, y)Draw a point.
rect
(x, y, w, h, *radii, tl, tr, br, bl, mode)Draw a rectangle.
square
(x, y, extent, mode)Draw a square.
rectMode
(mode)Change the way parameters are interpreted to draw rectangles.
quad
(x1, y1, x2, y2, x3, y3, x4, y4)Draw a quadrilateral.
triangle
(x1, y1, x2, y2, x3, y3)Draw a triangle.
polygon
(x, y, holes, close)Draw a polygon.
geometry
(shape)Draw a Shapely geometry.
bezier
(x1, y1, x2, y2, x3, y3, x4, y4)Draws a Bezier curve
bezierPoint
(a, b, c, d, t)Evaluates the Bezier at point
t
for pointsa
,b
,c
,d
. ThebezierTangent
(a, b, c, d, t)Calculates the tangent of a point on a Bezier curve.
-
shape
(shp, mask_lines, mask_points)Draw a shape.
sketch
(sub_sketch)Draw the content of another Vsketch.
vpype
(pipeline)Execute a vpype pipeline on the current sketch.
display
(paper, pen_up, colorful, axes, grid, unit, fig_size)Display the sketch on screen using matplotlib.
save
(file, device, *None, format, color_mode, layer_label, paper_size, velocity, quiet)Save the current sketch to a SVG or HPGL file.
random
(a, b)Return a random number with an uniform distribution between specified bounds.
Return a random number according to a gaussian distribution with a mean of 0 and a
randomSeed
(seed)Set the seed for
random()
andrandomGaussian()
.noise
(x, y, z, grid_mode)Returns the Perlin noise value at specified coordinates.
noiseDetail
(lod, falloff)Adjusts parameters of the Perlin noise function.
noiseSeed
(seed)Set the random seed for
noise()
.lerp
(start, stop, amt)static Interpolate between two numbers or arrays.
map
(value, start1, stop1, start2, stop2)static Map a value from one range to the other.
easing
(value, mode, start1, stop1, start2, stop2, low_dead, high_dead, param)static Map a value from one range to another, using an easing function.
textMode
(mode)Controls how text is laid out.
text
(text, x, y, *None, width, font, size, mode, align, line_spacing, justify)Add text to your sketch!
Members
- detail(epsilon: float | str) None #
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 asbezierDetail()
orcurveDetail()
.Examples
detail()
accepts string values with unit:>>> vsk = Vsketch() >>> vsk.detail("1mm")
A float input is interpretted as CSS pixels:
>>> vsk.detail(1.)
- Parameters:
epsilon -- maximum length of segments approximating curved elements (may be a string value with units -- float value are interpreted as CSS pixels
- size(width: float | str, height: float | str | None = None, landscape: bool = False, center: bool = True) None #
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
andheight
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 -- page width or page forwat specifier if
h
is omittedheight -- page height
landscape -- rotate page size by 90 degrees if True
center -- if False, automatic centering is disabled
- stroke(c: int) None #
Set the current stroke color.
- Parameters:
c (strictly positive int) -- the color (e.g. layer) to use for path
- strokeWeight(weight: int) None #
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
- strokeJoin(join_style: str) None #
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"
.See also
- Parameters:
join_style (
"round"
,"mitre"
, or"bevel"
) -- join style to use
- fill(c: int) None #
Set the current fill color. :param c: the color (e.g. layer) to use for fill :type c: strictly positive int
- penWidth(width: float | str, layer: int | None = None) 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 -- pen width
layer -- if provided, ID of the layer for which the pen width must be set (otherwise the default pen width is changed)
- resetMatrix() vsketch.utils.ResetMatrixContextManager #
Reset the current transformation matrix.
It can also be used as a context manager. In this case,
pushMatrix()
and its associatedpopMatrix()
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
- pushMatrix() vsketch.utils.MatrixPopper #
Push the current transformation matrix onto the matrix stack.
Each call to
pushMatrix()
should be matched by exactly one call topopMatrix()
to maintain consistency. Alternatively, the context manager returned bypushMatrix()
can be used to automatically callpopMatrix()
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
- scale(sx: float | str, sy: float | str | None = None) 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 -- scale factor along x axis (can be a string with units)
sy -- scale factor along y axis (can be a string with units) or None, in which case the same value as sx is used
- rotate(angle: float, degrees: bool = False) None #
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 -- the angle of the rotation in radian (or degrees if
degrees=True
)degrees -- if True, the input is interpreted as degree instead of radians
- translate(dx: float, dy: float) None #
Apply a translation to the current transformation matrix.
- Parameters:
dx -- translation along X axis
dy -- translation along Y axis
- line(x1: float, y1: float, x2: float, y2: float) None #
Draw a line.
- Parameters:
x1 -- X coordinate of starting point
y1 -- Y coordinate of starting point
x2 -- X coordinate of ending point
y2 -- Y coordinate of ending point
- circle(x: float, y: float, diameter: float | None = None, radius: float | None = None, mode: str | None = None) None #
Draw a circle.
The level of detail used to approximate the circle is controlled by
detail()
. As for theellipse()
function, the way arguments are interpreted is influenced by the mode set withellipseMode()
or themode
argument.See also
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 -- x coordinate of the center
y -- y coordinate of the center
diameter -- circle diameter (or None if using radius)
radius -- circle radius (or None if using diameter
mode -- one of ‘center’, ‘radius’, ‘corner’, ‘corners’
- ellipse(x: float, y: float, w: float, h: float, mode: str | None = None) None #
Draw an ellipse.
The way
x
,y
,w
, andh
parameters are interpreted depends on the current ellipse mode.By default,
x
andy
set the location of the ellipse center,w
sets its width, andh
sets its height. The way these parameters are interpreted can be changed with theellipseMode()
function (which changes the default for subsequent calls toellipse()
) or themode
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 -- by default, x coordinate of the ellipse center
y -- by default, y coordinate of the ellipse center
w -- by default, the ellipse width
h -- by default, the ellipse height
mode -- “corner”, “corners”, “radius”, or “center” (see
ellipseMode()
)
- arc(x: float, y: float, w: float, h: float, start: float, stop: float, degrees: bool | None = False, close: str | None = 'no', mode: str | None = None) None #
Draw an arc.
The way
x
,y
,w
, andh
parameters are interpreted depends on the current ellipse mode (seeellipse()
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, andpie
connects the two endings with the arc center.See also
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 -- by default, X coordinate of the associated ellipse center
y -- by default, Y coordinate of the associated ellipse center
w -- by default, width of the associated ellipse
h -- by default, height of the associated ellipse
start -- angle to start the arc (in radians)
stop -- angle to stop the arc (in radians)
degrees -- set to True to use degrees for start and stop angles (default: False)
close -- “no”, “chord” or “pie” (default: “no”)
mode -- “corner”, “corners”, “radius”, or “center” (see
ellipseMode()
)
- ellipseMode(mode: str) None #
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 -- one of “center”, “radius”, “corner”, “corners”.
- point(x: float, y: float) None #
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 -- X coordinate
y -- Y coordinate
- rect(x: float, y: float, w: float, h: float, *radii: float, tl: float | None = None, tr: float | None = None, br: float | None = None, bl: float | None = None, mode: str | None = None) None #
Draw a rectangle.
The way
x
,y
,w
, andh
parameters are interpreted depends on the current rectBy default,
x
andy
set the location of the upper-left corner,w
sets the width, andh
sets the height. The way these parameters are interpreted can be changed with therectMode()
function (which changes the default for subsequent calls torect()
) or themode
argument (which only affects this call).The optional parameters
tl
,tr
,br
andbl
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 -- by default, x coordinate of the top-left corner
y -- by default, y coordinate of the top-left corner
w -- by default, the rectangle width
h -- by default, the rectangle height (same as width if not provided)
tl -- top-left corner radius (0 if not provided)
tr -- top-right corner radius (same as tl if not provided)
br -- bottom-right corner radius (same as tr if not provided)
bl -- bottom-left corner radius (same as br if not provided)
mode -- “corner”, “corners”, “radius”, or “center” (see
rectMode()
)
- square(x: float, y: float, extent: float, mode: str | None = None) None #
Draw a square.
As for the
rect()
function, the way arguments are interpreted is influenced by the mode set withrectMode()
or themode
argument.See also
Example
>>> vsk = Vsketch() >>> vsk.square(2, 2, 2.5)
- Parameters:
x -- X coordinate of top-left corner
y -- Y coordinate of top-left corner
extent -- width and height of the square
mode -- “corner”, “radius”, or “center” (see
rectMode()
) — note that the “corners” mode is meaningless for this function, and is interpreted as the “corner” mode
- rectMode(mode: str) None #
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.
Example
>>> vsk = Vsketch() >>> vsk.rectMode("center") >>> vsk.square(3, 3, 1.5) >>> vsk.rect(2, 2, 3.5, 1)
- Parameters:
mode -- one of “corner”, “corners”, “center”, “radius”.
- quad(x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float) None #
Draw a quadrilateral.
Example
>>> vsk = Vsketch() >>> vsk.quad(0, 0, 1, 3.5, 4.5, 4.5, 3.5, 1)
- Parameters:
x1 -- X coordinate of the first vertex
y1 -- Y coordinate of the first vertex
x2 -- X coordinate of the second vertex
y2 -- Y coordinate of the second vertex
x3 -- X coordinate of the third vertex
y3 -- Y coordinate of the third vertex
x4 -- X coordinate of the last vertex
y4 -- Y coordinate of the last vertex
- triangle(x1: float, y1: float, x2: float, y2: float, x3: float, y3: float) None #
Draw a triangle.
Example
>>> vsk = Vsketch() >>> vsk.triangle(2, 2, 2, 3, 3, 2.5)
- Parameters:
x1 -- X coordinate of the first corner
y1 -- Y coordinate of the first corner
x2 -- X coordinate of the second corner
y2 -- Y coordinate of the second corner
x3 -- X coordinate of the third corner
y3 -- Y coordinate of the third corner
- polygon(x: Iterable[float] | Iterable[complex] | Iterable[Sequence[float]], y: Iterable[float] | None = None, holes: Iterable[Iterable[Sequence[float]]] = (), close: bool = False) None #
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:
x -- X coordinates or iterable of size-2 points (if
y
is omitted)y -- Y coordinates
holes -- list of holes inside the polygon
close -- the polygon is closed if True
- geometry(shape: Any) None #
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
- bezier(x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float) None #
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.
See also
- Parameters:
x1 -- X coordinate of the first anchor point
y1 -- Y coordinate of the first anchor point
x2 -- X coordinate of the first control point
y2 -- Y coordinate of the first control point
x3 -- X coordinate of the second control point
y3 -- Y coordinate of the second control point
x4 -- X coordinate of the second anchor point
y4 -- Y coordinate of the second anchor point
- bezierPoint(a: float, b: float, c: float, d: float, t: float) float #
Evaluates the Bezier at point
t
for pointsa
,b
,c
,d
. The parametert
varies between 0 and 1,a
andd
are points on the curve, andb
andc
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 att
.See also
- Parameters:
a -- coordinate of the first point of the curve
b -- coordinate of the first control point
c -- coordinate of the second control point
d -- coordinate of the second point of the curve
t -- value between 0 and 1
- Returns:
evaluated coordinate on the bezier curve
- bezierTangent(a: float, b: float, c: float, d: float, t: float) float #
Calculates the tangent of a point on a Bezier curve.
See also
- Parameters:
a -- coordinate of the first point of the curve
b -- coordinate of the first control point
c -- coordinate of the second control point
d -- coordinate of the second point of the curve
t -- value between 0 and 1
- Returns:
evaluated tangent on the bezier curve
- createShape() vsketch.shape.Shape #
- shape(shp: vsketch.shape.Shape, mask_lines: bool | None = None, mask_points: bool | None = None) None #
Draw a shape.
Draw a shape, including its area, lines, and points. If a
fill()
layer is active, it is used for the area. Likewise, the currentpenWidth()
is used for points (seepoints()
).By default, the shape’s lines and points are masked by the its area if a fill layer is active (such as to avoid unwanted interaction with the hatch fill), and left unmasked if not. This behaviour can be overridden using the
mask_lines
andmask_points
parameters.- Parameters:
shp -- the shape to draw
mask_lines -- controls whether the shape’s line are masked by its area (default: True if fill active, otherwise False)
mask_points -- controls whether the shape’s points are masked by its area (default: True if fill active, otherwise False)
- sketch(sub_sketch: Vsketch) None #
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 -- sketch to draw in the current sketch
- vpype(pipeline: str) None #
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 withvpype()
(e.g.vsk.vpype("crop 1cm 1cm 10cm 10cm")
.vpype is unaware of the automatic centering mechanism built in
size()
,display()
andsave()
. The pipeline is applied on the un-centered geometries. In some case, it may be useful to passcenter=False
tosize()
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 -- vpype pipeline to apply to the sketch
- display(paper: bool = True, pen_up: bool = False, colorful: bool = False, axes: bool = False, grid: bool = False, unit: str = 'px', fig_size: tuple[float, float] | None = None) None #
Display the sketch on screen using matplotlib.
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)
Additional options may occasionaly be useful:
>>> vsk.display(axes=True, grid=True, unit="cm")
- Parameters:
paper -- if True, the sketch is laid out on the desired page size (default: True)
pen_up -- if True, the pen-up trajectories will be displayed (default: False)
colorful -- if True, use one color per path instead of per layer (default: False)
axes -- if True, labelled axes are displayed (default: False)
grid -- if True, a grid is displayed (default: False)
unit -- use a specific unit for the axes (default: “px”)
fig_size -- specify the figure size
- save(file: str | TextIO, device: str | None = None, *, format: str | None = None, color_mode: str = 'layer', layer_label: str = '%d', paper_size: str | None = None, velocity: float | None = None, quiet: bool = False) None #
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’sopen()
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 tosize()
. If multiple configurations match the page size, the first one is used. In case of ambiguity, it is recommendande to specifypaper_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 -- destination SVG file (can be a file path or text-based IO stream)
device -- (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 -- (SVG only) define a template for layer naming (use %d for layer ID)
paper_size -- (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 withsize()
)velocity -- (HPGL only) if provided, a VS command will be emitted with the provided velocity
quiet -- (HPGL only) if set to True, silence plotter configuration and paper loading instructions
- random(a: float, b: float | None = None) float #
Return a random number with an uniform distribution between specified bounds.
See also
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 -- if b is provided: low bound, otherwise: high bound
b -- high bound
- Returns:
the random value
- randomGaussian() float #
Return a random number according to a gaussian distribution with a mean of 0 and a standard deviation of 1.0.
See also
- Returns:
the random value
- randomSeed(seed: int) None #
Set the seed for
random()
andrandomGaussian()
.By default,
Vsketch
instance are initialized with a random seed. By explicitly setting the seed, the sequence of number returned byrandom()
andrandomGaussian()
will be reproduced predictably.Note that each
Vsketch
instance has it’s own random state and will not affect other instances.- Parameters:
seed -- the seed to use
- noise(x: float, y: float | None = None, z: float | None = None, grid_mode: bool = True) float #
- noise(x: Sequence[float] | np.ndarray, y: None | float | Sequence[float] | np.ndarray = None, z: None | float | Sequence[float] | np.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
, andz
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
, andz
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.
See also
- 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
- noiseDetail(lod: int, falloff: float | None = None) 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
Processing noiseDetail() doc
- Parameters:
lod -- number of octaves to use
falloff -- ratio of amplitude of one octave with respect to the previous one
- static lerp(start: float | complex | np.ndarray, stop: float | complex | np.ndarray, amt: float) float | complex | np.ndarray #
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:
start -- start value or array
stop -- end value or array
amt -- value between 0. and 1.
- Returns:
interpolated value or array
- static map(value: float | np.ndarray, start1: float, stop1: float, start2: float, stop2: float) float | np.ndarray #
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 -- value or array of value to re-map
start1 -- low bound of the value’s current range
stop1 -- high bound of the value’s current range
start2 -- low bound of the target range
stop2 -- high bound of the target range
- Returns:
the re-maped value or array
- static easing(value: float, mode: str = 'linear', start1: float = 0.0, stop1: float = 1.0, start2: float = 0.0, stop2: float = 1.0, low_dead: float = 0.0, high_dead: float = 0.0, param: float = 10) float #
- static easing(value: numpy.ndarray, mode: str = 'linear', start1: float = 0.0, stop1: float = 1.0, start2: float = 0.0, stop2: float = 1.0, low_dead: float = 0.0, high_dead: float = 0.0, param: float = 10) numpy.ndarray
Map a value from one range to another, using an easing function.
Easing functions specify the rate of change of a parameter over time (or any other input). This function provides a way to apply an easing function on a value.
The
mode
parameter specify the easing function to use. Check theeasing
example for a list and a demo of all easing functions.The input value may be a single float or a Numpy array of float.
Input values are clamped to
[start1, stop1]
and mapped to[start2, stop2]
. Further, a lower and/or high dead zone can be specified as a fraction of the range usinglow_dead
andhigh_dead
. Ifdelta = stop1 - start1
, the actual input range is[start1 + low_dead * delta, stop1 - high_dead * delta]
.The
param
argument is used by some easing functions.- Parameters:
value -- input value(s)
mode -- easing function to use
start1 -- start of the input range
stop1 -- end of the input range
start2 -- start of the output range
stop2 -- end of the output range
low_dead -- lower dead zone (fraction of input range)
high_dead -- higher dead zone (fraction of input range)
param -- parameter use
- Returns:
converted value(s)
- textMode(mode: str) None #
Controls how text is laid out.
- There are two options for the text mode:
“transform”, where the font itself is subject to the current transform matrix, including translation, scaling, rotation, skewing and flipping.
“label”, where the text is only scaled and translated using the current transform matrix, but is not rotated, skewed or flipped.
See also
- Parameters:
mode (
"transform"
, or"label"
) -- text layout mode to use.
- text(text: str, x: float = 0.0, y: float = 0.0, *, width: float | None = None, font: str = 'futural', size: float | str = '12pt', mode: str | None = None, align: str = 'left', line_spacing: float = 1.0, justify: bool = False) None #
Add text to your sketch!
This can add either lines or blocks of text to your sketch. The default is to add a line of text, but if width is specified, then a block of text will be created that width.
The fonts available are the same as those available from vpype.
A
size
of 1.0 means the maximum font height will be as long as a line 1.0 long (given current transform).- The
mode
here is special. There are two options for the mode: “transform”, where the font itself is subject to the current transform matrix, including translation, scaling, rotation, skewing and flipping.
“label”, where the text is only moved and scaled using the current transform matrix, but is not rotated, skewed or flipped.
The text mode can also be set using
textMode()
.align
controls the text alignment, and can be “left”, “right” or “center”.line_spacing
andjustify
are only used whenwidth
is specified, and they allow you to control the line spacing and justification of your block of text.See also
- Parameters:
text -- text to add to the sketch
x -- the x coordinate of the anchor point for the text. This sets either the leftmost, rightmost, or centre point of the first line of text, depending on the value of
align
.y -- the y coordinate of the anchor point for the text. This sets the centre line of the first line of text.
width -- if given, wraps the text to this width and creates a text block, not a text line. A text block may be multi-line.
size -- the font size. It is highly recommended to give this as a float (in document units) in “transform” mode, and an absolute size such as “12pt” in “label” mode.
font -- a vpype font
mode -- “transform” or “label”, see description for details.
align -- “left”, “right”, or “center”. See also x and y args.
line_spacing -- Gives the line spacing for a text block, in multiples of size. No effect without width.
justify -- whether to justify the text block. No effect without width.
- The
- class vsketch.Shape(vsk: vsketch.Vsketch)#
Reusable and drawable shape with support for boolean operations.
A shape is a reusable graphical element made of polygons, lines and points. Shapes are built using primitives in a very similar way to how
Vsketch
works with the added capability of using boolean drawing operation (union, difference, intersection, or exclusive union).Shapes must be created using a
Vsketch
instance:shape = vsk.createShape()
Shapes consist of an area (which may be disjoint and have holes), a set of lines, and a set of points (both of which may be empty). Lines and points are added to the shape using the
line()
,bezier()
, andpoint()
methods.The shape’s area can be built with primitives similar to that of
Vsketch
:shape.square(0, 0, 1, mode="radius") shape.square(0.5, 0.5, 1, mode="radius")
By default, an union operation applied when new primitives are added. Other boolean operations are available. For example, a hole can be punched in the shape as follows:
shape.circle(0, 0, 0.5, mode="radius", op="difference")
Finally, a shape can be drawn to a sketch with the
Vsketch.shape()
method:vsk.stroke(1) vsk.fill(2) vsk.shape(shape)
Vsketch.shape()
can control whether the lines and points which intersects with the shape’s area are masked. For example, it’s best to enable masking when the shape’s area is to be hatched. SeeVsketch.shape()
’s documentation for details.Note
It is helpful to understand the fundamental difference between a
Vsketch
andShape
instance.At any point in time,
Vsketch
instances contains a set of paths which correspond exactly to what the plotter will draw and is considered read-only (One of the reason for that is that scaling existing geometries would invalidate any hatching).On the other hand, a
Shape
instance is an abstract geometrical representation which can, at any point in time, be further modified, for example using thedifference
mode (which subtracts a primitive from the existing shape). This abstract representation is turned into actual plotter line work (including hatching if enabled withVsketch.fill()
) only when it is drawn in a sketch usingVsketch.shape()
. At this point, the final scaling is applied (based on the current transformation matrix), the hatching (if any) is computed, points are transformed into small circles (seeVsketch.point()
), and the resulting, ready-to-be-plotted paths are added to the sketch.Overview
Methods# point
(x, y)Add a point to the shape.
line
(x1, y1, x2, y2)Add a line to the shape.
circle
(x, y, diameter, radius, mode, op)Add a circle to the shape.
ellipse
(x, y, w, h, mode, op)Add an ellipse to the shape.
arc
(x, y, w, h, start, stop, degrees, close, mode, op)Add an arc to the shape.
rect
(x, y, w, h, *radii, tl, tr, br, bl, mode, op)Add a rectangle to the shape.
square
(x, y, extent, mode, op)Add a square to the shape.
quad
(x1, y1, x2, y2, x3, y3, x4, y4, op)Add a quadrilateral to the shape.
triangle
(x1, y1, x2, y2, x3, y3, op)Add a triangle to the shape.
polygon
(x, y, holes, close, op)Add a polygon to the shape.
geometry
(shape, op)Add a Shapely geometry to the shape.
bezier
(x1, y1, x2, y2, x3, y3, x4, y4)Add a Bezier curve to the shape.
shape
(shape, op)Combine the shape with another shape.
Members
- point(x: float, y: float) None #
Add a point to the shape. :param x: X coordinate of the point :param y: Y coordinate of the point
- line(x1: float, y1: float, x2: float, y2: float) None #
Add a line to the shape.
- Parameters:
x1 -- X coordinate of starting point
y1 -- Y coordinate of starting point
x2 -- X coordinate of ending point
y2 -- Y coordinate of ending point
- circle(x: float, y: float, diameter: float | None = None, radius: float | None = None, mode: str | None = None, op: BooleanOperation = 'union') None #
Add a circle to the shape.
The level of detail used to approximate the circle is controlled by
Vsketch.detail()
. As for theellipse()
function, the way arguments are interpreted is influenced by themode
argument or the mode set withVsketch.ellipseMode()
of theVsketch
instance used to create the shape.This function support multiple boolean mode with the
op
argument:union
(default, the circle is added to the shape),difference
(the circle is cut off the shape),intersection
(only the overlapping part of the circle is kept in the shape), orsymmetric_difference
(only the none overlapping parts of the shape and circle are kept).Example
>>> import vsketch >>> vsk = vsketch.Vsketch() >>> vsk.circle(0, 0, 10) # by default, diameter is used >>> vsk.circle(0, 0, radius=5) # radius can be specified instead
- Parameters:
x -- x coordinate of the center
y -- y coordinate of the center
diameter -- circle diameter (or None if using radius)
radius -- circle radius (or None if using diameter
mode -- one of ‘center’, ‘radius’, ‘corner’, ‘corners’
op -- one of ‘union’, ‘difference’, ‘intersection’, or ‘symmetric_difference’
- ellipse(x: float, y: float, w: float, h: float, mode: str | None = None, op: BooleanOperation = 'union') None #
Add an ellipse to the shape.
The way
x
,y
,w
, andh
parameters are interpreted depends on the current ellipse mode of theVsketch
instance used to create the shape.By default,
x
andy
set the location of the ellipse center,w
sets its width, andh
sets its height. The way these parameters are interpreted can be changed with themode
argument or theVsketch.ellipseMode()
function of theVsketch
instance used to create the shape.This function support multiple boolean mode with the
op
argument:union
(default, the ellipse is added to the shape),difference
(the ellipse is cut off the shape),intersection
(only the overlapping part of the ellipse is kept in the shape), orsymmetric_difference
(only the none overlapping parts of the shape and ellipse are kept).See also
Examples
By default, the argument are interpreted as the center coordinates as well as the width and height:
>>> import vsketch >>> vsk = vsketch.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 -- by default, x coordinate of the ellipse center
y -- by default, y coordinate of the ellipse center
w -- by default, the ellipse width
h -- by default, the ellipse height
mode -- “corner”, “corners”, “radius”, or “center” (see
ellipseMode()
)op -- one of ‘union’, ‘difference’, ‘intersection’, or ‘symmetric_difference’
- arc(x: float, y: float, w: float, h: float, start: float, stop: float, degrees: bool | None = False, close: str | None = 'no', mode: str | None = None, op: BooleanOperation = 'union') None #
Add an arc to the shape.
The way
x
,y
,w
, andh
parameters are interpreted depends on the current ellipse mode (seeellipse()
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, andpie
connects the two endings with the arc center.This function support multiple boolean mode with the
op
argument:union
(default, the arc is added to the shape),difference
(the arc is cut off the shape),intersection
(only the overlapping part of the arc is kept in the shape), orsymmetric_difference
(only the none overlapping parts of the shape and arc are kept).See also
Example
>>> import vsketch >>> vsk = vsketch.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 -- by default, X coordinate of the associated ellipse center
y -- by default, Y coordinate of the associated ellipse center
w -- by default, width of the associated ellipse
h -- by default, height of the associated ellipse
start -- angle to start the arc (in radians)
stop -- angle to stop the arc (in radians)
degrees -- set to True to use degrees for start and stop angles (default: False)
close -- “no”, “chord” or “pie” (default: “no”)
mode -- “corner”, “corners”, “radius”, or “center” (see
ellipseMode()
)op -- one of ‘union’, ‘difference’, ‘intersection’, or ‘symmetric_difference’
- rect(x: float, y: float, w: float, h: float, *radii: float, tl: float | None = None, tr: float | None = None, br: float | None = None, bl: float | None = None, mode: str | None = None, op: BooleanOperation = 'union') None #
Add a rectangle to the shape.
The way
x
,y
,w
, andh
parameters are interpreted depends on the current rect mode of theVsketch
instance used to create the shape.By default,
x
andy
set the location of the upper-left corner,w
sets the width, andh
sets the height. The way these parameters are interpreted can be changed with themode
argument or therectMode()
function of theVsketch
instance used to create this shape.The optional parameters
tl
,tr
,br
andbl
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.This function support multiple boolean mode with the
op
argument:union
(default, the rectangle is added to the shape),difference
(the rectangle is cut off the shape),intersection
(only the overlapping part of the rectangle is kept in the shape), orsymmetric_difference
(only the none overlapping parts of the shape and rectangle are kept).See also
Examples
By default, the argument are interpreted as the top left corner as well as the width and height:
>>> import vsketch >>> vsk = vsketch.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 -- by default, x coordinate of the top-left corner
y -- by default, y coordinate of the top-left corner
w -- by default, the rectangle width
h -- by default, the rectangle height (same as width if not provided)
tl -- top-left corner radius (0 if not provided)
tr -- top-right corner radius (same as tl if not provided)
br -- bottom-right corner radius (same as tr if not provided)
bl -- bottom-left corner radius (same as br if not provided)
mode -- “corner”, “corners”, “radius”, or “center” (see
rectMode()
)op -- one of ‘union’, ‘difference’, ‘intersection’, or ‘symmetric_difference’
- square(x: float, y: float, extent: float, mode: str | None = None, op: BooleanOperation = 'union') None #
Add a square to the shape.
As for the
rect()
function, the way arguments are interpreted is influenced by the mode set with themode
argument or theVsketch.rectMode()
of theVsketch
instance used to create the shape.This function support multiple boolean mode with the
op
argument:union
(default, the square is added to the shape),difference
(the square is cut off the shape),intersection
(only the overlapping part of the square is kept in the shape), orsymmetric_difference
(only the none overlapping parts of the shape and square are kept).See also
Example
>>> import vsketch >>> vsk = vsketch.Vsketch() >>> vsk.square(2, 2, 2.5)
- Parameters:
x -- X coordinate of top-left corner
y -- Y coordinate of top-left corner
extent -- width and height of the square
mode -- “corner”, “radius”, or “center” (see
rectMode()
) — note that the “corners” mode is meaningless for this function, and is interpreted as the “corner” modeop -- one of ‘union’, ‘difference’, ‘intersection’, or ‘symmetric_difference’
- quad(x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float, op: BooleanOperation = 'union') None #
Add a quadrilateral to the shape.
This function support multiple boolean mode with the
op
argument:union
(default, the quad is added to the shape),difference
(the quad is cut off the shape),intersection
(only the overlapping part of the quad is kept in the shape), orsymmetric_difference
(only the none overlapping parts of the shape and quad are kept).See also
Example
>>> import vsketch >>> vsk = vsketch.Vsketch() >>> vsk.quad(0, 0, 1, 3.5, 4.5, 4.5, 3.5, 1)
- Parameters:
x1 -- X coordinate of the first vertex
y1 -- Y coordinate of the first vertex
x2 -- X coordinate of the second vertex
y2 -- Y coordinate of the second vertex
x3 -- X coordinate of the third vertex
y3 -- Y coordinate of the third vertex
x4 -- X coordinate of the last vertex
y4 -- Y coordinate of the last vertex
op -- one of ‘union’, ‘difference’, ‘intersection’, or ‘symmetric_difference’
- triangle(x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, op: BooleanOperation = 'union') None #
Add a triangle to the shape.
This function support multiple boolean mode with the
op
argument:union
(default, the triangle is added to the shape),difference
(the triangle is cut off the shape),intersection
(only the overlapping part of the triangle is kept in the shape), orsymmetric_difference
(only the none overlapping parts of the shape and triangle are kept).See also
Example
>>> import vsketch >>> vsk = vsketch.Vsketch() >>> vsk.triangle(2, 2, 2, 3, 3, 2.5)
- Parameters:
x1 -- X coordinate of the first corner
y1 -- Y coordinate of the first corner
x2 -- X coordinate of the second corner
y2 -- Y coordinate of the second corner
x3 -- X coordinate of the third corner
y3 -- Y coordinate of the third corner
op -- one of ‘union’, ‘difference’, ‘intersection’, or ‘symmetric_difference’
- polygon(x: Iterable[float] | Iterable[Sequence[float]] | Iterable[complex], y: Iterable[float] | None = None, holes: Iterable[Iterable[Sequence[float]]] = (), close: bool = False, op: BooleanOperation = 'union') None #
Add a polygon to the shape.
This function support multiple boolean mode with the
op
argument:union
(default, the polygon is added to the shape),difference
(the polygon is cut off the shape),intersection
(only the overlapping part of the polygon is kept in the shape), orsymmetric_difference
(only the none overlapping parts of the shape and polygon are kept).See also
Examples
A single iterable of size-2 sequence can be used:
>>> import vsketch >>> vsk = vsketch.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:
x -- X coordinates or iterable of size-2 points (if
y
is omitted)y -- Y coordinates
holes -- list of holes inside the polygon
close -- the polygon is closed if True
op -- one of ‘union’, ‘difference’, ‘intersection’, or ‘symmetric_difference’
- geometry(shape: LineString | LinearRing | MultiPolygon | MultiLineString | Polygon, op: BooleanOperation = 'union') None #
Add a Shapely geometry to the shape.
This function should accept any of LineString, LinearRing, MultiPolygon, MultiLineString, or Polygon.
This function support multiple boolean mode with the
op
argument:union
(default, the geometry is added to the shape),difference
(the geometry is cut off the shape),intersection
(only the overlapping part of the geometry is kept in the shape), orsymmetric_difference
(only the none overlapping parts of the shape and geometry are kept).See also
- Parameters:
shape (Shapely geometry) -- a supported shapely geometry object
op -- one of ‘union’, ‘difference’, ‘intersection’, or ‘symmetric_difference’
- bezier(x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float) None #
Add a Bezier curve to the shape.
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.
The level of detail of the bezier curve is controlled using the
Vsketch.detail()
method on theVsketch
instance used to create the shape.- Parameters:
x1 -- X coordinate of the first anchor point
y1 -- Y coordinate of the first anchor point
x2 -- X coordinate of the first control point
y2 -- Y coordinate of the first control point
x3 -- X coordinate of the second control point
y3 -- Y coordinate of the second control point
x4 -- X coordinate of the second anchor point
y4 -- Y coordinate of the second anchor point
- shape(shape: Shape, op: BooleanOperation = 'union') None #
Combine the shape with another shape.
This function can combine another shape with this shape, using various boolean mode. When
op
is set to"union"
, theshape
’s polygons, lines and points are merged into this instance. When using other operations ("difference"
,"intersection"
, or"symmetric_difference"
), the corresponding operation is applied withshape
’s polygon, but its lines and points are ignored.- Parameters:
shape -- the shape to combine
op -- one of ‘union’, ‘difference’, ‘intersection’, or ‘symmetric_difference’
- class vsketch.SketchClass#
Base class for sketch managed with the
vsk
CLI tool.Subclass must override
draw()
andfinalize()
.Overview
Methods# display
(*args, **kwargs)class Execute the sketch class and display the results using
Vsketch.display()
.draw
(vsk)abc Draws the sketch.
finalize
(vsk)abc Finalize the sketch before export.
Members
- classmethod display(*args: Any, **kwargs: Any) None #
Execute the sketch class and display the results using
Vsketch.display()
.All parameters are forwarded to
Vsketch.display()
.
- abstract draw(vsk: vsketch.vsketch.Vsketch) None #
Draws the sketch.
This function must be implemented by subclasses.
- abstract finalize(vsk: vsketch.vsketch.Vsketch) None #
Finalize the sketch before export.
This function must be implemented by subclasses.
- class vsketch.Param(value: _T, min_value: _T | None = None, max_value: _T | None = None, *, choices: Iterable[_T] | None = None, step: None | float | int = None, unit: str = '', decimals: int | None = None)#
Bases:
Generic
[_T
]Generic parameter for
SketchClass
.This class implements a generic parameter for
SketchClass
instances. Parameters can be interacted with in thevsk
viewer and support functionalities such as saved configuration and parameter space exploration withvsk save
.