Two.js
A two-dimensional drawing api meant for modern browsers. It is renderer agnostic enabling the same api to render in multiple contexts: webgl, canvas2d, and svg.
Home • Releases • Examples • Documentation • Change Log • Help
Usage
Download the latest minified library and include it in your html.
It can also be installed via npm, Node Package Manager:
npm install –save two.js
Alternatively see how to build the library yourself.
Here is boilerplate html in order to draw a spinning rectangle in two.js:
This will give you a number of libraries that the development of Two.js relies on. If for instance you only use the SvgRenderer then you can really cut down on the file size by excluding the other renderers. To do this, modify /utils/build.js to only add the files you’d like. Then run:
node ./utils/build
And the resulting /build/two.js and /build/two.min.js will be updated to your specification.
Using ES6 Imports
As of version v0.7.5+ Two.js is compatible with EcmaScript 6 imports. This is typically employed in contemporary frameworks like React and Angular as well as bundling libraries like webpack, esbuild, and gulp. This adaptation of the boilerplate can be found on CodeSandbox:
import React, { useEffect, useRef } from “react”;
import Two from “two.js”;
export default function App() {
var domElement = useRef();
useEffect(setup, []);
function setup() {
var two = new Two({
fullscreen: true,
autostart: true
}).appendTo(domElement.current);
var rect = two.makeRectangle(two.width / 2, two.height / 2, 50, 50);
two.bind(“update”, update);
return unmount;
function unmount() {
two.unbind(“update”);
two.pause();
domElement.current.removeChild(two.renderer.domElement);
}
function update() {
rect.rotation += 0.001;
}
}
return
;Now in a JavaScript file setup your Two.js scenegraph and save out frames whenever you need to:
var { createCanvas, Image } = require(‘canvas’);
var Two = require(‘two.js’)
var fs = require(‘fs’);
var path = require(‘path’);
var width = 800;
var height = 600;
var canvas = createCanvas(width, height);
Two.Utils.shim(canvas, Image);
var time = Date.now();
var two = new Two({
width: width,
height: height,
domElement: canvas
});
var rect = two.makeRectangle(width / 2, height / 2, 50, 50);
rect.fill = ‘rgb(255, 100, 100)’;
rect.noStroke();
two.render();
var settings = { compressionLevel: 3, filters: canvas.PNG_FILTER_NONE };
fs.writeFileSync(path.resolve(__dirname, ‘./images/rectangle.png’), canvas.toBuffer(‘image/png’, settings));
console.log(‘Finished rendering. Time took: ‘, Date.now() – time);
process.exit();
Change Log
Two.js has been in operation since 2012. For a full list of changes from its first alpha version built with Three.js to the most up-to-date tweaks. Check out the wiki here.