xyz-tools/gcode-preview
Über uns
A simple GCode parser & previewer lib with 3D printing in mind. Written in Typescript.
EntwicklerwerkzeugeGemessener Sternzuwachs
- in 24h
- 0
- in 7 days
- +1
- in 15 days
- +1
- in 1 month
- Verlauf wird gesammelt
Nettoänderungen in überlappenden Zeiträumen, keine Tagessummen. Fehlende Messwerte bleiben leer. Sterne zeigen Interesse, nicht Qualität.
README.md
OriginalGCode Preview

A simple G-code parser & viewer lib with 3D printing in mind. Written in Typescript.
Join us on discord
Feature summary
- multi-color
- tube geometry
- g2/g3 arcs
- streaming (progressive rendering from a
ReadableStream) - thumbnail preview
- build volume
- orthographic camera
- slicer detection (PrusaSlicer family, Cura, Simplify3D, Slic3r)
- per-point extrusion width & line height from
;WIDTH:/;HEIGHT:slicer comments (adaptive layer height) - drag & drop
- examples for various frameworks
Demo
Minimal demo
try it out: https://codepen.io/remcoder/pen/PwYVXBg
Batteries included
Click to see the full-fledged demo:
Installation
The 3.0 release is currently in alpha. To install the latest alpha:
npm install gcode-preview@alpha
For the current stable 2.x release:
npm install gcode-preview
GCode Preview depends on three.js and supports three >=0.166.0 <0.186.0.
Module format (3.0)
The package is ESM-only. Import from gcode-preview; the only other public
package path is gcode-preview/package.json. Deep imports such as
gcode-preview/dist/gcode-preview.es.js are no longer supported, and the
legacy UMD build / GCodePreview browser global has been removed.
TypeScript supports node16, nodenext, and bundler module resolution.
Legacy moduleResolution: "node" (node10) currently resolves the root import
through types, but it is no longer tested or supported: TypeScript 6
deprecates it and TypeScript 7 removes it. Switch to bundler for frontend
apps, or node16/nodenext for Node.
Consumers compile with their own TypeScript, not the library's. The packaging test typechecks the published declarations on both TypeScript 6 and 5.9, in all three supported resolution modes, with no extra ambient type packages.
For native browser modules, map three in an import map and load
dist/gcode-preview.es.js as a module. When self-hosting, copy the entire
dist directory, including any chunks. The library adds nothing to the
document beyond the canvas you hand it.
Quick start
import { GCodePreview } from 'gcode-preview';
const preview = new GCodePreview({
canvas: document.querySelector('canvas'),
extrusionColor: 'hotpink'
});
// draw a diagonal line
const gcode = 'G0 X0 Y0 Z0.2\nG1 X42 Y42 E10';
preview.processGCode(gcode);
G-code can also be streamed in and rendered progressively:
const response = await fetch('benchy.gcode');
await preview.processGCodeStream(response.body);
Constructor options
The main options accepted by new GCodePreview({ ... }) (see the
API docs for the full reference):
canvas— the canvas element to render tobuildVolume— renders the build volume (see below)- colors:
backgroundColor,extrusionColor,travelColor,topLayerColor,lastSegmentColor,boundingBoxColor - render toggles:
renderExtrusion,renderTravel,renderTubes,disableGradient - geometry:
lineWidth,lineHeight,extrusionWidth— per-point dimensions from;WIDTH:/;HEIGHT:slicer comments always win (adaptive layer height renders correctly);lineHeight/extrusionWidthfill in for points without them, and built-in defaults (0.6 width / 0.2 height) apply last - layer range:
startLayer,endLayer - camera:
orthographic,initialCameraPosition - streaming:
liveRenderInterval(throttles progressive rendering) - arcs:
arcChordTolerance(tessellation precision for G2/G3) - misc:
droppable(drag & drop g-code files onto the canvas),keepLines,minLayerThreshold
After construction, most rendering properties live on the scene manager and can
be changed at runtime, e.g. preview.sceneManager.renderTubes = true, followed
by a re-render.
API Docs
Check the full API documentation at https://gcode-preview.web.app/docs
Vue.js / React / Svelte integration
There's a Vue.js example that has a Vue component to wrap the library.
@Zeng95 provided a React & Typescript example that has a React component to wrap the library.
There is a Svelte example with a Svelte component.
Feature description
Supported G-code commands
The interpreter currently handles:
| Command | Meaning |
|---|---|
G0 / G1 |
linear move |
G2 / G3 |
clockwise / counter-clockwise arc |
G20 / G21 |
set units to inches / millimeters |
G28 |
home |
G31 |
straight probe |
G38.2–G38.5 |
probe family |
G92 |
set position |
G92.1 |
reset coordinate system offsets |
T0–T7 |
tool selection |
Commands without a handler are parsed but ignored by the interpreter.
G92.2 and G92.3 are not supported.
Standalone ;WIDTH:<mm> and ;HEIGHT:<mm> comments (emitted by PrusaSlicer,
SuperSlicer, OrcaSlicer and Bambu Studio) are picked up by the slicer metadata
pipeline and set the extrusion width and line height of the moves that follow,
so prints sliced with adaptive layer height render with the true dimensions of
each move. A dimension change does not split the path: each point keeps the
dimensions it was added under, so the tube tapers from the old dimensions to
the new ones over the one segment where the change happens. Dimensions resolve
per point: the slicer-announced value wins, the lineHeight /
extrusionWidth options fill in for points without one, and the built-in
defaults (0.6 width / 0.2 height) apply last.
Multi-color support
GCode files that were sliced for a multi-tool system can be previewed as such. Pass an array of colors as the extrusionColor constructor option (or assign preview.sceneManager.extrusionColor at runtime), where the index in the array corresponds to the index of the tool: T0..T7.
example:
extrusionColor: ['hotpink', 'indigo', 'lime']
Here, T0 is hotpink, T1 is indigo and T2 is lime.
Supported systems include:
- Prusa MMU1/2/3 and XL
- Bambulab AMS & AMS lite
- Enraged Rabbit Carrot Feeder (ERCF)
- IDEX machines
- toolchangers
- 3D Chameleon
- Virtual tools (color mixing)
- and possibly more
Render extrusion as tubes
Extrusions are rendered as tubes by default; pass renderTubes: false as a
constructor option to render flat lines (it can also be toggled at runtime
via preview.sceneManager.renderTubes):
new GCodePreview({ canvas, renderTubes: false });
G2/G3 arc support
Thanks to @Sindarius arc commands are now supported, which means gcode processed by ArcWelder should be rendered correctly.
Thumbnail preview
Thumbnail previews as generated by PrusaSlicer are detected and parsed. In the gcode these are found in comments, enclosed between 'thumbnail begin' and 'thumbnail end'. The images are encoded as base64 strings but split over multiple lines. These are now parsed and patched back together, but still kept a base64. This allows easy use in the browser for us as data urls.
Thumbnail Preview as generated by PrusaSlicer
The thumbnails can be accessed like this:
gcodePreview.parser.metadata.thumbnails['220x124']
Thumbnails have a .src property that will create a usable data url from the base64 string.
See an example in the demo source.
Build volume
The build volume will be rendered if the buildVolume parameter is passed. It has the following type:
buildVolume: {
x: number;
y: number;
z: number;
smallGrid?: boolean;
}
Negative dimensions are clamped to 0.
example:

Development
To develop on gcode-preview run:
npm i && npm run dev
This runs the demo app which is fairly complete in using the libs features.
If you don't need the demo app, just run npm run dev:watch.
Both build a dev bundle in the dist directory.
Note the dev bundle:
- is not minified
- has no type defs (.d.ts)
Submitting a PR
See CONTRIBUTING.md for the full guidelines. In short, before submitting a PR run:
npm run check(test + typeCheck + lint)npm run buildfor a production buildnpm run test:coverage— CI requires 100% coverage for every file undersrc/
To auto-fix simple issues:
npm run lint:fixornpm run prettier:fix
Production builds
For working on production builds you can use:
npm run demowhich does a prod build and launches the demo app using local server- or just
npm run buildornpm run build:watch
Feedback
If you have found a bug or if have an idea for a feature, don't hesitate to create an issue on GitHub or talk to us on Discord.
Contributing
Want to help out? We are open to your ideas and always willing to get you started! talk to us on Discord.
- maybe there is an open issue that appeals to you?
- other things that are always helpful:
- testing different gcode files, from different slicers
- reporting bugs! Screenshot == ❤️
- making GCode Preview suitable for different printer types, like Deltas, Belt printers, IDEX, etc. Even CNC machines
- documentation & examples
- unit tests
Contributors
- ❤️ Thank you @0xTHAC0 for adding the orthographic camera.
- ❤️ Thank you @sophiedeziel for rendering extrusion as tubes and creating a new interpreter.
- ❤️ Thank you @RickRyan26 and @Sindarius for implementing G2/G3 arc support.
- ❤️ Thank you @Zeng95 for providing a React & Typescript example.
- ❤️ Thank you @raulodev for parser and preview fixes.
- ❤️ Thank you @TimTheBig for dependency and tooling updates.
Known issues
Preview doesn't render in Brave
This is caused by the device recognition shield in Brave. By changing the setting for "Device Recognition" in Shield settings to "Allow all device recognition attemps" or "Only block cross-site device recognition attemps" you should not get this error. https://github.com/mrdoob/three.js/issues/16904
Compile errors from @types/three on TypeScript 6
If you are on TypeScript 6 and have @types/three 0.181.0 – 0.183.1
pinned, tsc reports around 50 duplicate-identifier errors (TS2403, TS2687,
TS2717, TS6200) inside node_modules/@webgpu/types/dist/index.d.ts.
Any one of these resolves it:
- upgrade
@types/threeto 0.184.0 or newer (recommended), - or stay on
@types/three0.180.x or older, - or set
"skipLibCheck": truein yourtsconfig.json— on by default in most scaffolded projects, which is why this rarely shows up.
Brought to you by XYZ Tools
11-11-2024 This repo was moved to a brand new org which is a collaboration between @remcoder and @sophiedeziel for everything 3D printing related.
Sponsors
A big thanks to these sponsors for their contributions.
Donate
If you want to show gratitude you can always buy me beer/coffee/filament via ko-fi or PayPal ^_^
License
This project is licensed under the MIT License.
Ähnliche Projekte entdecken
Wird geladen…
