svg-turtle
v0.1.9
Published
a turtle graphics library with SVG output
Downloads
16
Readme
svg-turtle
a turtle graphics library with SVG output
svg-turtle
is a small JavaScript library (written in TypeScript) to create turtle graphics with SVG output. While it may well be used to create "ordinary" graphics, it is primarily intended to create projects for cutting plotters.
(this project is currently under active development, please stay tuned - it is planned to be finished by end of July)
NPM users: please consider the Github README for the latest description of this package (as updating the docs would otherwise always require a new NPM package version)
Just a small note: if you like this module and plan to use it, consider "starring" this repository (you will find the "Star" button on the top right of this page), so that I know which of my repositories to take most care of.
Installation
svg-turtle
may be used as an ECMAScript module (ESM), a CommonJS or AMD module or from a global variable.
You may either install the package into your build environment using NPM with the command
npm install svg-turtle
or load the plain script file directly
<script src="https://unpkg.com/svg-turtle"></script>
Access
How to access the package depends on the type of module you prefer
- ESM (or Svelte):
import { Graphic } from 'svg-turtle'
- CommonJS:
const SVGTurtle = require('svg-turtle')
- AMD:
require(['svg-turtle'], (SVGTurtle) => {...})
Alternatively, you may access the global variable SVGTurtle
directly.
Usage within Svelte
For Svelte it is recommended to import the package within a module context:
<script context="module">
import Graphic from 'svg-turtle'
</script>
<script>
let SVG = new Graphic().moveTo(10,10).draw(10).curveRight(90,10).draw(10).asSVG()
</script>
Usage as ECMAscript Module
If you prefer ESMs, just import the library and use it:
<script>
import { Graphic } from 'svg-turtle'
window.onload = function () {
let SVG = new Graphic().moveTo(10,10).draw(10).curveRight(90,10).draw(10).asSVG()
...
}
</script>
Usage as CommonJS or AMD Module (or as a global Variable)
Let's assume that you already "required" or "imported" (or simply loaded) the module according to your local environment. In that case, you may use it as follows:
<script>
const { Graphic } = SVGTurtle
window.onload = function () {
let SVG = new Graphic().moveTo(10,10).draw(10).curveRight(90,10).draw(10).asSVG()
...
}
</script>
Example
A simple example is available on the Svelte REPL - feel free to play with it!
More examples can be found below.
API Reference
As shown in the code examples above, every graphic is represented by an instance of class Graphic
- each of which may contain multiple "paths".
A typical workflow looks as follows:
- create an instance of class
Graphic
, - define one or multiple "paths",
- render the instance as SVG - if need be, with proper scaling for cutting plotters
exported Types
type TUR_Location = number
represents an optionally signed finite number to be used as an x or y coordinatetype TUR_Dimension = number
represents a finite number ≥ 0 to be used as a dimension (i.e., width or height)type TUR_Angle = number
represents an optionally signed finite number to be used as an angle (given in degrees, positive values rotate clockwise, negative ones counterclockwise)type TUR_Color = string
represents a literal CSS/SVG-compliant color specification (such as "red" or "#FF0000")type TUR_Lineature = 'solid'|'dotted'|'dashed'
represents a specifies line typetype TUR_Join = 'bevel'|'miter'|'round'
represents a line join typetype TUR_Cap = 'butt'|'round'|'square'
represents a line end typetype TUR_PathOptionSet = {
x?:TUR_Location, y?:TUR_Location, Direction?:TUR_Angle,
Width?:TUR_Dimension, Color?:TUR_Color,
Lineature?:TUR_Lineature, Join?:TUR_Join, Cap?:TUR_Cap
}
represents a set of options which may be used to initialize a new pathtype TUR_Position = { x:TUR_Location, y:TUR_Location }
represents a position of the turtle, given by its x and y coordinates - but whithout specifying its orientationtype TUR_Alignment = { x:TUR_Location, y:TUR_Location, Direction:TUR_Angle }
represents a position and orientation of the turtle, given by its x and y coordinates and its orientation measured in degrees against the x-axis (positive values describe a clockwise, negative ones a counterclockwise rotation)
Class Graphic
Class Graphic
has a single parameterless constructor. After instantiation (or, later, after a reset
), its settings contain the following defaults:
x,y
:0,0
(at coordinate origin)Direction
:0
(in direction of the x-axis)Width
: 1Color
:#000000
Lineature
:solid
Join
:round
Cap
:round
Many methods return the instance they were applied to in the end - this may be used to immediately concatenate multiple method invocations (sometimes called a fluent API)
reset ():Graphic
sets turtle position, orientation and line properties to their defaults (as shown above)beginPath (PathOptionSet?:TUR_PathOptionSet):Graphic
starts a new path, beginning with the current turtle position, orientation and line properties, optionally overwritten by any settings given inPathOptionSet
turn (Anglee:TUR_Angle):Graphic
rotates the turtle relative to its current direction by the givenAngle
(specified in degrees). Positive angles rotate clockwise, negative ones counterclockwise. This method may be invoked outside an active pathturnTo (Angle:TUR_Angle):Graphic
rotates the turtle "absolutely" (i.e. relative to the x-axis) to the givenAngle
(specified in degrees). Positive angles describe a clockwise, negative ones a counterclockwise rotation. This method may be invoked outside an active pathturnLeft (Angle:TUR_Angle):Graphic
rotates the turtle counterclockwise by the givenAngle
(specified in degrees), equivalent toturn(-Angle)
. This method may be invoked outside an active pathturnRight (Angle:TUR_Angle):Graphic
rotates the turtle clockwise by the given Angle (specified in degrees). This method is just a synonym forturn(Angle)
. It may be invoked outside an active pathmove (Distance:TUR_Location):Graphic
moves the turtle "relatively" (i.e., starting from its current position) in the current direction forDistance
units without drawing. Positive values forDistance
move forward, negative ones move backward. This method may be invoked outside an active pathmoveTo (x:TUR_Location, y:TUR_Location):Graphic
moves the turtle "absolutely" (i.e., measured from the origin) to the given position (keeping its current orientation) without drawing. This method may be invoked outside an active pathdraw (Distance:TUR_Location):Graphic
moves the turtle "relatively" (i.e., starting from its current position) in the current direction forDistance
units drawing a straight line. Positive distances move forward, negative ones backward. If invoked outside an active path, a new path with the current turtle position, orientation and line style is starteddrawTo (x:TUR_Location, y:TUR_Location):Graphic
moves the turtle "absolutely" (i.e., measured from the origin) to the given position (keeping its current orientation) drawing a straight line. If invoked outside an active path, a new path with the current turtle position, orientation and line style is startedcurveLeft (Angle:TUR_Angle, rx:TUR_Dimension, ry?:TUR_Dimension):Graphic
moves the turtle "relatively" (i.e., starting from its current position) drawing a counterclockwise circular or elliptical arc for the givenAngle
with radiusrx
(in the current turtle direction) andry
(perpendicular to the current turtle direction). Ifry
is omitted, it defaults torx
. Positive angles move the turtle forward, negative angles backward. Finally, the turtle is positioned at the end of the arc and oriented tangentially to the arc. If invoked outside an active path, a new path with the current turtle position, orientation and line style is startedcurveRight (Angle:TUR_Angle, rx:TUR_Dimension, ry?:TUR_Dimension):Graphic
moves the turtle "relatively" (i.e., starting from its current position) drawing a clockwise circular or elliptical arc for the givenAngle
with radiusrx
(in the current turtle direction) andry
(perpendicular to the current turtle direction). Ifry
is omitted, it defaults torx
. Positive angles move the turtle forward, negative angles backward. Finally, the turtle is positioned at the end of the arc and oriented tangentially to the arc. If invoked outside an active path, a new path with the current turtle position, orientation and line style is startedendPath ():Graphic
ends the currently active path (if one is active). This method is "idempotent", i.e., it is save to end an already ended pathclosePath ():Graphic
closes the currently active path (if one is active), drawing a straight line to its starting point, and then ends it. This method is "idempotent", i.e., it is save to close an already ended pathcurrentPosition ():TUR_Position
returns the current turtle position. This method may be used to remember a specific point on a turtle's path and move the turtle back to this position laterpositionAt (Position:TUR_Position):Graphic
moves the turtle to the given position without changing its direction. It differs frommoveTo
insofar as you have to specify aTUR_Position
rather than two separate coordinatescurrentAlignment ():TUR_Alignment
returns the current turtle position and orientation. This method may be used to remember a specific point and direction on a turtle's path and move the turtle back to this position with the given orientation lateralignAt (Alignment:TUR_Alignment):Graphic
moves the turtle to the given position and changes its directionLimits ():{ xMin:number, yMin:number, xMax:number, yMax:number}
returns current estimated viewport limits, based on the paths theGraphic
instance containspublic asSVG (
Unit?:'px'|'mm'|'cm'|'in',
xMin?:number,yMin?:number, xMax?:number,yMax?:number
):string
returns the SVG code for the underlyingGraphic
instance and all its paths, using the givenxMin
,xMax
,yMin
andyMax
values as viewport limits - any missing limit is estimated from the paths theGraphic
instance contains. If the target system (e.g., a web browser) supports it, the resulting SVG will rendered using the givenUnit
(which defaults topx
)public asSVGwith72dpi (
Unit?:'px'|'mm'|'cm'|'in',
xMin?:number,yMin?:number, xMax?:number,yMax?:number
):string
returns the SVG code for the underlyingGraphic
instance and all its paths, using the givenxMin
,xMax
,yMin
andyMax
values as viewport limits - any missing limit is estimated from the paths theGraphic
instance contains. In contrast toasSVG
, this method scales the output such that all coordinates and dimensions are multiples of 1/72 inch (depending on the given unit which defaults tomm
)
Usage with "Cricut Design Space"
The "Cricut Design Space" does not respect any units given in an SVG's width
and height
attributes but expects the numeric coordinates to be multiples of 1/72 of an inch. It is therefore recommended to export any turtle graphics using the asSVGwith72dpi
method which scales the output as required by the application (based on the provided unit).
Typical Workflow when using "Cricut Design Space"
Typically, within "Cricut Design Space", you will first
- upload the SVG generated by svg-turtle and then
- place it on the canvas for later plotting and cutting
Now, you should
- "ungroup" the full SVG in order to get the separate paths,
- these paths may now be individually selected in order to assign the proper tools (such as a knife for cutting or a scoring stylus or wheel for scoring)
If need be, you may also
- duplicate selected paths (for multiple cutting or scoring rounds) and then
- align all duplicates to their original left and top edges
Before plotting, you should not forget to
- attach all paths again for proper positioning on mat
Your project is now ready to be sent to your plotter.
Further Examples
All of them can be found on the Svelte REPL - ready to play with!
Build Instructions
You may easily build this package yourself.
Just install NPM according to the instructions for your platform and follow these steps:
- either clone this repository using git or download a ZIP archive with its contents to your disk and unpack it there
- open a shell and navigate to the root directory of this repository
- run
npm install
in order to install the complete build environment - execute
npm run build
to create a new build
You may also look into the author's build-configuration-study for a general description of his build environment.