svg-turtle
TypeScript icon, indicating that this package has built-in type declarations

0.1.9 • Public • Published

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.

simple box

(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!

simple Example

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 coordinate
  • type 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 type
  • type TUR_Join = 'bevel'|'miter'|'round'
    represents a line join type
  • type TUR_Cap = 'butt'|'round'|'square'
    represents a line end type
  • type 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 path
  • type 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 orientation
  • type 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: 1
  • Color: #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 in PathOptionSet
  • turn (Anglee:TUR_Angle):Graphic
    rotates the turtle relative to its current direction by the given Angle (specified in degrees). Positive angles rotate clockwise, negative ones counterclockwise. This method may be invoked outside an active path
  • turnTo (Angle:TUR_Angle):Graphic
    rotates the turtle "absolutely" (i.e. relative to the x-axis) to the given Angle (specified in degrees). Positive angles describe a clockwise, negative ones a counterclockwise rotation. This method may be invoked outside an active path
  • turnLeft (Angle:TUR_Angle):Graphic
    rotates the turtle counterclockwise by the given Angle (specified in degrees), equivalent to turn(-Angle). This method may be invoked outside an active path
  • turnRight (Angle:TUR_Angle):Graphic
    rotates the turtle clockwise by the given Angle (specified in degrees). This method is just a synonym for turn(Angle). It may be invoked outside an active path
  • move (Distance:TUR_Location):Graphic
    moves the turtle "relatively" (i.e., starting from its current position) in the current direction for Distance units without drawing. Positive values for Distance move forward, negative ones move backward. This method may be invoked outside an active path
  • moveTo (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 path
  • draw (Distance:TUR_Location):Graphic
    moves the turtle "relatively" (i.e., starting from its current position) in the current direction for Distance 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 started
  • drawTo (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 started
  • curveLeft (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 given Angle with radius rx (in the current turtle direction) and ry (perpendicular to the current turtle direction). If ry is omitted, it defaults to rx. 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 started
  • curveRight (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 given Angle with radius rx (in the current turtle direction) and ry (perpendicular to the current turtle direction). If ry is omitted, it defaults to rx. 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 started
  • endPath ():Graphic
    ends the currently active path (if one is active). This method is "idempotent", i.e., it is save to end an already ended path
  • closePath ():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 path
  • currentPosition ():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 later
  • positionAt (Position:TUR_Position):Graphic
    moves the turtle to the given position without changing its direction. It differs from moveTo insofar as you have to specify a TUR_Position rather than two separate coordinates
  • currentAlignment ():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 later
  • alignAt (Alignment:TUR_Alignment):Graphic
    moves the turtle to the given position and changes its direction
  • Limits ():{ xMin:number, yMin:number, xMax:number, yMax:number}
    returns current estimated viewport limits, based on the paths the Graphic instance contains
  • public asSVG (
      Unit?:'px'|'mm'|'cm'|'in',
      xMin?:number,yMin?:number, xMax?:number,yMax?:number
    ):string
    returns the SVG code for the underlying Graphic instance and all its paths, using the given xMin, xMax, yMin and yMax values as viewport limits - any missing limit is estimated from the paths the Graphic instance contains. If the target system (e.g., a web browser) supports it, the resulting SVG will rendered using the given Unit (which defaults to px)
  • public asSVGwith72dpi (
      Unit?:'px'|'mm'|'cm'|'in',
      xMin?:number,yMin?:number, xMax?:number,yMax?:number
    ):string
    returns the SVG code for the underlying Graphic instance and all its paths, using the given xMin, xMax, yMin and yMax values as viewport limits - any missing limit is estimated from the paths the Graphic instance contains. In contrast to asSVG, this method scales the output such that all coordinates and dimensions are multiples of 1/72 inch (depending on the given unit which defaults to mm)

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!

Hexagon Star KochCurve
Hexagon Star Koch Curve

Build Instructions

You may easily build this package yourself.

Just install NPM according to the instructions for your platform and follow these steps:

  1. either clone this repository using git or download a ZIP archive with its contents to your disk and unpack it there
  2. open a shell and navigate to the root directory of this repository
  3. run npm install in order to install the complete build environment
  4. 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.

License

MIT License

Readme

Keywords

Package Sidebar

Install

npm i svg-turtle

Weekly Downloads

8

Version

0.1.9

License

MIT

Unpacked Size

355 kB

Total Files

19

Last publish

Collaborators

  • arozek