Top Related Projects
JavaScript 3D Library.
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey
p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
Quick Overview
Two.js is a lightweight 2D drawing and animation library for the web. It provides a simple and intuitive API for creating and manipulating shapes, paths, and groups in both SVG and Canvas renderers. Two.js is designed to be easy to use while still offering powerful features for creating interactive graphics and animations.
Pros
- Cross-renderer compatibility (SVG and Canvas)
- Lightweight and performant
- Easy-to-use API for creating and animating shapes
- Extensive documentation and examples
Cons
- Limited 3D capabilities compared to other graphics libraries
- Smaller community and ecosystem compared to more established libraries
- May not be suitable for complex, high-performance graphics applications
- Limited built-in physics and advanced animation features
Code Examples
Creating a simple shape:
var two = new Two({
fullscreen: true,
autostart: true
}).appendTo(document.body);
var circle = two.makeCircle(two.width / 2, two.height / 2, 50);
circle.fill = '#FF8000';
circle.stroke = 'orangered';
Animating a shape:
var rect = two.makeRectangle(two.width / 2, two.height / 2, 100, 100);
rect.fill = 'rgb(0, 200, 255)';
rect.noStroke();
two.bind('update', function(frameCount) {
rect.rotation = frameCount / 60;
});
Creating a custom shape:
var points = [
new Two.Vector(0, 0),
new Two.Vector(100, 0),
new Two.Vector(100, 100)
];
var triangle = two.makePath(points);
triangle.fill = 'red';
triangle.closed = true;
triangle.translation.set(two.width / 2, two.height / 2);
Getting Started
- Include Two.js in your project:
<script src="https://cdnjs.cloudflare.com/ajax/libs/two.js/0.7.0/two.min.js"></script>
- Create a Two.js instance and add it to the DOM:
var elem = document.getElementById('draw-shapes');
var params = { width: 285, height: 200 };
var two = new Two(params).appendTo(elem);
- Create and manipulate shapes:
var circle = two.makeCircle(72, 100, 50);
var rect = two.makeRectangle(213, 100, 100, 100);
circle.fill = '#FF8000';
circle.stroke = 'orangered';
rect.fill = 'rgba(0, 200, 255, 0.75)';
two.update();
Competitor Comparisons
JavaScript 3D Library.
Pros of Three.js
- More comprehensive 3D rendering capabilities
- Larger community and ecosystem, with extensive documentation and examples
- Support for advanced features like WebGL, shaders, and complex 3D models
Cons of Three.js
- Steeper learning curve due to its complexity and extensive API
- Larger file size and potentially higher performance overhead for simpler projects
Code Comparison
Two.js (2D rendering):
var two = new Two({
fullscreen: true,
autostart: true
}).appendTo(document.body);
var circle = two.makeCircle(two.width / 2, two.height / 2, 50);
circle.fill = '#FF8000';
circle.stroke = 'orangered';
Three.js (3D rendering):
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.SphereGeometry(1, 32, 32);
const material = new THREE.MeshBasicMaterial({ color: 0xFF8000 });
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
Pros of PixiJS
- More comprehensive and feature-rich, offering advanced rendering capabilities and a wider range of graphics options
- Better performance for complex animations and large numbers of sprites
- Larger community and ecosystem, with more plugins, extensions, and resources available
Cons of PixiJS
- Steeper learning curve due to its more extensive API and features
- Larger file size, which may impact load times for smaller projects
- Potentially overkill for simple 2D graphics or basic animations
Code Comparison
Two.js:
var two = new Two({
fullscreen: true,
autostart: true
}).appendTo(document.body);
var circle = two.makeCircle(72, 100, 50);
circle.fill = '#FF8000';
circle.noStroke();
PixiJS:
const app = new PIXI.Application({ resizeTo: window });
document.body.appendChild(app.view);
const circle = new PIXI.Graphics();
circle.beginFill(0xFF8000);
circle.drawCircle(72, 100, 50);
app.stage.addChild(circle);
Both libraries allow for easy creation of 2D graphics, but PixiJS offers more advanced features and better performance for complex projects. Two.js has a simpler API and is more lightweight, making it suitable for basic 2D graphics and animations.
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
Pros of Fabric.js
- More comprehensive feature set, including advanced object manipulation and interactive canvas elements
- Robust SVG parsing and rendering capabilities
- Extensive documentation and larger community support
Cons of Fabric.js
- Larger file size and potentially heavier performance impact
- Steeper learning curve due to more complex API
Code Comparison
Two.js:
var two = new Two({
fullscreen: true,
autostart: true
}).appendTo(document.body);
var circle = two.makeCircle(72, 100, 50);
circle.fill = 'rgb(255, 100, 100)';
circle.noStroke();
Fabric.js:
var canvas = new fabric.Canvas('canvas');
var circle = new fabric.Circle({
radius: 50,
fill: 'rgb(255, 100, 100)',
left: 72,
top: 100
});
canvas.add(circle);
Both libraries allow for easy creation of shapes, but Fabric.js provides more built-in options for object manipulation and interactivity. Two.js has a simpler API, making it easier to get started with basic shapes and animations. Fabric.js offers more advanced features out of the box, such as object selection, scaling, and rotation, which may require additional implementation in Two.js.
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
Pros of EaselJS
- More comprehensive and feature-rich, offering a wider range of tools for complex animations and interactive graphics
- Better suited for game development with built-in support for sprite sheets and sound
- Larger community and ecosystem, providing more resources and third-party extensions
Cons of EaselJS
- Steeper learning curve due to its extensive API and features
- Heavier file size, which may impact load times and performance for simpler projects
- Less focus on modern web technologies like SVG and WebGL
Code Comparison
EaselJS:
var stage = new createjs.Stage("canvas");
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
circle.x = 100;
circle.y = 100;
stage.addChild(circle);
Two.js:
var two = new Two({ type: Two.Types.canvas }).appendTo(document.body);
var circle = two.makeCircle(100, 100, 50);
circle.fill = 'red';
two.update();
Both libraries allow for easy creation of shapes and basic animations, but EaselJS requires more setup code for the stage and offers more granular control over graphics, while Two.js provides a more concise API for simple shapes and animations.
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey
Pros of Paper.js
- More comprehensive and feature-rich vector graphics library
- Supports both SVG and Canvas rendering
- Extensive documentation and examples
Cons of Paper.js
- Steeper learning curve due to its complexity
- Larger file size, which may impact load times
Code Comparison
Paper.js:
paper.setup('myCanvas');
var path = new paper.Path();
path.strokeColor = 'black';
path.moveTo(new paper.Point(30, 75));
path.lineTo(new paper.Point(30, 25));
Two.js:
var two = new Two({ fullscreen: true }).appendTo(document.body);
var line = two.makeLine(30, 75, 30, 25);
line.stroke = 'black';
two.update();
Both libraries allow for creating vector graphics, but Paper.js offers more advanced features and a more object-oriented approach. Two.js, on the other hand, provides a simpler API for basic shapes and animations.
Paper.js is better suited for complex vector graphics projects, while Two.js is ideal for simpler, performance-focused applications. The choice between the two depends on the specific requirements of your project and your familiarity with vector graphics programming.
p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
Pros of p5.js
- Larger community and more extensive documentation
- Broader range of features, including 3D graphics and sound processing
- Easier for beginners with a simpler API and more intuitive functions
Cons of p5.js
- Heavier library size, which may impact load times and performance
- Less focused on vector graphics compared to Two.js
- May be overwhelming for projects that only require basic 2D graphics
Code Comparison
p5.js:
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
ellipse(200, 200, 50, 50);
}
Two.js:
var two = new Two({
fullscreen: true,
autostart: true
}).appendTo(document.body);
var circle = two.makeCircle(200, 200, 25);
circle.fill = '#FF8000';
Both libraries allow for easy creation of basic shapes, but p5.js uses a more procedural approach with separate setup and draw functions, while Two.js uses a more object-oriented style. p5.js is generally more verbose but may be easier for beginners to understand, while Two.js offers a more concise syntax for creating and manipulating shapes.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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.
<script src="js/two.min.js"></script>
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:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="js/two.min.js"></script>
</head>
<body>
<script>
var two = new Two({
fullscreen: true,
autostart: true
}).appendTo(document.body);
var rect = two.makeRectangle(two.width / 2, two.height / 2, 50 ,50);
two.bind('update', function() {
rect.rotation += 0.001;
});
</script>
</body>
</html>
Custom Build
Two.js uses nodejs in order to build source files. You'll first want to install that. Once installed open up a terminal and head to the repository folder:
cd ~/path-to-repo/two.js
npm install
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 <div ref={domElement} />;
}
In addition to importing, the published packages of Two.js include the specific modules. So, if necessary you can import specific modules from the source code and bundle / minify for yourself like so:
import { Vector } from 'two.js/src/vector.js';
// In TypeScript environments leave out the ".js"
// when importing modules directly. e.g:
import { Vector } from 'two.js/src/vector';
While useful, the main import of the Two
namespace imports all modules. So, there isn't yet proper tree shaking implemented for the library, though it's on the roadmap.
Running in Headless Environments
As of version v0.7.x
Two.js can also run in a headless environment, namely running on the server with the help of a library called Node Canvas. We don't add Node Canvas to dependencies of Two.js because it's not necessary to run it in the browser. However, it has all the hooks set up to run in a cloud environment. To get started follow the installation instructions on Automattic's readme. After you've done that run:
npm install canvas
npm install two.js
Now in a JavaScript file set up 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.polyfill(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();
Build Documentation
The Two.js website is bundled with this repository. Relying on Vuepress the repository generates a website based on numerous README.md
files housed in the wiki
directory. Use the following the node commands as follows:
npm run docs:generate // Generate README.md files for documentation from source code comments
npm run docs:dev // Creates a local server to generate all documentation
npm run docs:build // Builds out static site and associated files to wiki/.vuepress/dist
N.B: Vuepress is a legacy library and as such these commands rely on an older version of Node. Run nvm use
if you get errors. If you don't use Node Version Manager then see .nvmrc
to install the correct version of node on your local machine.
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.
And a big thank you to our sponsors who include:
Top Related Projects
JavaScript 3D Library.
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey
p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot