GithubHelp home page GithubHelp logo

jonobr1 / two.js Goto Github PK

View Code? Open in Web Editor NEW
8.2K 158.0 451.0 16.69 MB

A renderer agnostic two-dimensional drawing api for the web.

Home Page: https://two.js.org

License: MIT License

JavaScript 96.66% HTML 0.14% Vue 2.20% Stylus 0.91% Shell 0.02% TypeScript 0.06%
svg webgl javascript canvas scenegraph renderer html5 es6 2d rendering-engine vector-graphics bitmap-graphics text-rendering animation

two.js's Introduction

Two.js

NPM Package Build Size NPM Downloads

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.

HomeReleasesExamplesDocumentation • Change LogHelp

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.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();

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:

Epilogue Press

two.js's People

Contributors

adroitwhiz avatar alper-batioglu avatar awkor avatar brandonheyer avatar chrisdelbuck avatar crgk avatar dickinson0718 avatar elshialabeouf avatar eulertour avatar fchasen avatar ferm10n avatar gburlet avatar hellosimon avatar hlfcoding avatar iros avatar jonobr1 avatar kevin-nano avatar larrybotha avatar lgtm-migrator avatar masonblier avatar mik30s avatar ponychicken avatar salesan avatar spajker7 avatar tadeegan avatar timgates42 avatar tomconroy avatar tonzusj avatar trusktr avatar xixixao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

two.js's Issues

How to handle with elements wrapped with jQuery?

When trying to use an element selected with jQuery to create a two.js drawing playground, I have an error, since, as I understood, two.js requires only a pure unwrapped DOM element with a defined method 'appendChild()' on it. Is it not possible to support jQuery-wrapped elements?

Website examples

First time I saw the website I didn't even realize the sources were editable. Even on my retina pro, I can't see the sources and their canvases at the same time. Consider putting them side by side or at least after each other.

Publish the package on nuget

To increase the amount of users you should add the package on Nuget. This will enable Microsoft developers to easily install the package into their project. In the nuget package you can also add code to automatically add the script tag and some example code to the layout file etc. this gives the developers a quick start.

Let me know if you need any help or more info.

getBoundingClientRect behaviour

(copied from Two.Polygon Width & Height issue thread)

@jonobr1 On getBoundingClientRect, it seems to behave oddly on rotation, is this the expected behaviour?
untitled

(Rotated by Pi / 8).

Thanks for addressing this so quickly.

Changing tab/minimizing window

Hello, I have been playing with Two.js to make a multiplayer asteroids game (plug: http://asteroids.azurewebsites.net/ ) however I have noticed that when you minimize or change browser tab, the bind('update') event isn't triggered.

For a multiplayer game this is undesirable - is there a way to stop this behavior?

Simple rotation of an SVG

Hi! I like it very much! I'm a beginner and desperately looking to find an answer why the svg doesn't rotate. Your starter-bootstrap works well. The .svg shows up, but doesn't rotate or is on any pre-defined opacity. I could't find more than this post on flippinawesome.org where working with SVG are a bit explained.
Could you help me out?

<!doctype html>
<html>
  <head>
    <script src="two.min.js"></script>
  </head>
  <body>
        <div id="assets">
                <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
             width="1133.858px" height="1133.858px" viewBox="0 0 1133.858 1133.858" enable-background="new 0 0 1133.858 1133.858"
             xml:space="preserve">
        <path fill="#000" d="M610.333,648.842h-0.038L451.406,489.599l-150.861-0.157l-0.057,48.622l45.442,45.536l68.451,0.077
            l101.798,102.018l-0.076,68.863l45.448,45.543l48.615,0.057l0.168-151.203l0.033-0.038l-0.033-0.04L610.333,648.842z
             M502.165,378.181l-150.863-0.168l-0.051,48.621l45.448,45.536l67.355,0.072l163.328,163.697l-0.077,67.344l45.444,45.546
            l48.628,0.058l0.162-150.876l-0.021-0.002L502.165,378.181z M514.459,360.451l6.016,6.023l98.444,98.67l33.807-33.713l0.072-64.6
            l-100.23-100.46l-150.859-0.16l-0.052,48.631l45.44,45.537L514.459,360.451z M733.837,448.042l-64.603-0.07l-33.795,33.727
            l98.439,98.668l6.028,6.031l-0.073,67.371l45.438,45.539l48.618,0.052l0.166-150.854L733.837,448.042z"/>
        </svg>
        </div>
    <div class="scripts">
        <script>
          var two = new Two({
            fullscreen: true,
            autostart: true
          }).appendTo(document.body);

          var el = $('#assets svg')[0];
          var shape = two.interpret(el).center();
          shape.opacity=0.5;

          two.bind('update', function() {
            shape.rotation += 0.001;
          }).play();
        </script>
    </div>
  </body>
</html>

edit: typos

Clipping masks

I just got started with this library and found that it doesn't allow clipping masks, a very handy feature in vector graphics.

I basically wanted to ask if there's any workaround for that, and suggest it as a future enhancement.

Thanks for the good work!

The Need for Speed

Thanks for your last reply in the Support for Paths and Detection thread!

For my use case the SVG context is not the best, if that is what I needed then the awesome D3.js API would be what I would use. The harsh reality is that D3.js is horrible on mobile devices, for a jaw dropping test try the following canvas solution and then the D3 solution on desktop and then on an iPad:

canvas : http://soulwire.github.io/sketch.js/examples/particles.html
d3 : http://ggruiz.me/weeknd3/

I have been looking into the options for sometime and have had to except that the canvas and its enhancement webgl are what my app requires. I'm on a quest now to find the right API to make that possible.

The only thing that is SVG about my app is that the symbols come from an SVG origin. There are many symbols my app uses and I want users to be able to create and add their own, the best way to allow that is with SVG tools and the result SVG paths these tools produce. From there I parse the paths into JSON (or just parse the straight SVG Webfonts). Finally, specific sets of symbols, in JSON or Webfont format are activated and interpreted into Two objects and cached, using this promising new API I just discovered called Two ;-)

Once cached as Two objects I'm hoping that rendering a few hundred symbols (of a similar complexity as your "Interpreting SVG's" example uses) in the view will be fast and that interaction will be as quick on the iPad as the particles sample link above is.

Clipping path / Compound shape question

I'd like to dynamically create a new two.polygon which would be the intersection of two other already defined two.polygons. I understand there is no such capability in this library yet, is it right?

In that case, do you think it's achievable with some relative ease? (since I'm not really a programmer, although I'm learning pretty fast)

I'd be really glad for any advice on how to achieve this, some kind of a inspiration elsewhere, any kind of resource material. Thanks a lot!

ps: I've been trying to find a way how to post this privately, (to not flood these boards with my problems) but they (github) seem to have removed this option.

But I guess it might help someone else later. Not sure how to label it as a question though, sorry. :-/

Path ID to Polygon ID

Hi, first, thanks for this awesome awesome library :)

There's one little thing that I have to work around, even though it would be a pretty easy fix/improvement I think.

When I'm using the SVG Interpreter (great feature btw!), I'd like the final Two.Polygons have the same ID's as the original SVG paths. That way I can name them in Illustrator and have them easily accessible in the code with my own names, instead of dynamically generated (basically meaningless) numbers. That way I can always be sure that I'm selecting the right shapes from the group, when I need them selectively.

Could this be an optional parameter for the Two.Interpret method? Something like keepPathId = [true|false]

I'd try to do it on my own, but I'm pretty new to all this so I'm afraid I would screw it up somehow. :)

Thank you very much for consideration and keep up the great work.

Suggestion: Image example

I would love to see one or more examples of rendering images with different renderers, though I'm mostly interested in WebGL renderer.

It's always raster versus vector when in comes to renderers. If two.js is really a great solution for both, it can grow immensely in popularity. I personally don't know the correct way to use two.js for images.

Flickering/translated drawing issue with interactive drawing

I am using two.js for an interactive drawing widget, and I'm encountering an issue with flicker/accidentally translated shapes.

Here's a jsfiddle: http://jsfiddle.net/JSvhU/2/

If you hold down the mouse and draw for a while, you'll occasionally see flickers where the curve is getting drawn in the wrong location on the screen. The problem exists in Chrome, Safari, and Firefox on OS X, and it's worst on Firefox, then Safari, then Chrome. Firefox slows to a crawl.

Here is the code in question:

var two = new Two().appendTo(document.body).update();
var points = [];
var poly;
var active = false;

$(document).bind('mousedown', function(e) {
    poly = null;
    points = [e.pageX, e.pageY];
    active = true;
}).bind('mousemove', function(e) {
    if (!active) return; // only draw if mouse is down
    if (poly) two.remove(poly); // remove previously drawn poly

    points.push(e.pageX);
    points.push(e.pageY);
    points.push(true); // open poly

    poly = two.makeCurve.apply(two, points);

    points.pop(); // remove true/false value

    poly.noFill();
    poly.stroke = 'blue';

    two.update();
}).bind('mouseup', function(e) {
   active = false; 
   points = [];
});

I'm not sure if this is a limitation of two.js (e.g. size of points array is too big), or a problem with my code. Thoughts? I know I could draw lines as individual line segments instead of curves/polygons, but I'd like to be able to draw curves/polys in this way, too.

Two.Collection

I'm having a little trouble understanding how Two.Collections work and how to pass them to a two.polygon. The following gives me "undefined is not a function" -

var myCollection = new Two.Collection(300, 300, 300, 400, 400, 400, 400, 300);

var myPolygon = two.makePolygon();
newPolygon.vertices = myCollection;

Trying to do the same with a Two.Array gives me " has no method 'slice'".

I'm still pretty new to coding, so I'm probably missing something obvious about how collections, arrays and polygons are supposed to work together. What is it I'm missing or doing incorrectly?

Thanks!

FSM as a Tool Abstraction Layer in Two

NOTE: This is a continuance of the FSM topic that was started in Add DOM Events in Objects

This is my elaboration on how FSM would be good for two.js.

Right away, a FSM module in Two would provide a well known pattern for structuring tools and actions based on states, which pretty well everything slices and dices into. To use an analogy, if Two is the sea and Pointer Events are the sky then a well crafted tool solution is everything between the sky and sea. This provides the essential elements: the canvas, the events, the interaction.

I first appreciated FSMs as I was engineering my apps complex tool system, because what emerged from the engineering was essentially a state machine. I then saw that there were more developers talking about FSMs and then AngularJS recently embraced the FSM pattern in its UI-Router module.

Just to be clear, AngularJS uses a FSM for managing views that can have controllers designated to the views but that is different than the use Two would have. In Two a FSM would be used to manage tools, like for a game or drawing app, but if the FSM is generic enough it can be used for other purposes too.

One of the clearest examples I've seen of a FSM is in a recent game here where it is used to manage the complete game logic: http://codeincomplete.com/posts/2013/5/19/javascript_gauntlet_logic

Essentially, it might just be easy enough to plugin in a FSM API like this one: https://github.com/jakesgordon/javascript-state-machine

It seems like a FSM would just lend itself nicely to anyone wanting to build something robust with Two. Especially if it is as straightforward as the game logic above shows. Tools can get messy and ultimately everything is states with callbacks anyways so hey, there is a superb solution to leverage in the FSM pattern.

Configuration makes things flexible so another aspect I'm considering is defining a FSM as a JSON file. There are a few FSM APIs that allow this option, see the first two links below. I've also added another recent article that gets into the benefits of using a FSM as the third link below:

http://lamehacks.net/blog/implementing-a-state-machine-in-javascript
http://machinejs.maryrosecook.com

http://freshbrewedcode.com/jimcowart/2012/03/12/machina-js-finite-state-machines-in-javascript

'.children[0]' in documentation seems wrong

I've made a fiddle http://jsfiddle.net/BTnhC/1/
Though the cdn I'm using in the fiddle is not the latest version of two.js. I have experienced the same issue using the latest version in my own site.
The '.children[0]' part, when appending the Two object to the DOM seems wrong. If we omit it then the examples work for me.
This is a big issue for people trying to learn how to use Two.js

Failing to clone groups

When I clone() groups I get the following error: "Uncaught TypeError: Cannot read property 'type' of undefined". The code is:

      var newGroup = new Two.Group();
      two.add(newGroup);
      var cloneGroup = newGroup.clone()

clone() seems to work fine for Two.Vector and Two.Anchor, any ideas why I get this error?

Pan and Zoom

This is a question rather than an issue but it's the best place to ask.

I'm trying to add a pan and zoom feature to the game I'm making (with two). I've got the pan working fine, but i'm struggling with the zoom. Would some kind person mind giving a quick example of how to zoom the scene to the mouse coordinates like Google Maps please?

Easiest way to include text in polygons?

Hi,
I'm trying to include text inside circles and polygons in general. Is there a way to get access to the svg object from the two object, in order to add text to the polygon.

Two.Vector performance qualms

In an application I am toying with, almost 90% of my application time is spent in Backbone.js as a result of the x and y setters in Two.Vector.

Is this intentional?

In my case, removing these events firing solved my problem with no ill effect, but it still seemed a bit strange.

Support for monitors not running 60Hz

On the example/documentation site it says:

The first is two.play(); which calls two.update(); at 60fps. This rate, however, will slowdown if there's too much content to render per frame."

This is only true on 60Hz monitor.

When using a 24 or 120Hz monitor, everything gets speed up or down when using .play(), since requestAnimationFrame is locked to the refreshrate of the screen in use.

This solution to this, would also solve the issue with animation speed on low performing hardware.

This issue can easily be tested in Chrome by disabling vsync in chrome://flags

Prepare shape objects for a group without having them on screen...yet

Edit: This is definitely a question, not an issue!

I hope this is the right place for this! Using two.js, what could be the best approach to properly create shape objects (like using makeLine, makeRectangle, etc) without having them appear in the scene immediately, add them to a group, then have the shapes appear in the scene thereafter? I'm sure that question in a bit unclear, so here is an example:

/*...*/
function: buildShape()
{
  this.shape = two.makeGroup();
  this.shape.translation.set(this.X,this.Y);

  var unitBody = two.makeRectangle(0,0,28,16);
  var pod = two.makeCirucle(0,0,this.podSize);
  var barrel = two.makeLine(0,0,this.barrelLen,0);

  this.shape.add(unitBody,pod,barrel);
}
/*...*/

While the above works just fine in code and eventual outcome, there is a split second that the three shape objects appear at the top left of the screen (0px, 0px) since that's what I have to do for them to appear properly in the group after adding them.

Without having to copy/paste your make functions so that I can manipulate them to not place the shape on the screen, is there any other way to do this?

Thanks in advance for an awesome library!

SVG Interpret Quality

Is there a way to increase the quality within the 'subdivide' function for SVG interpretations?

i.e. to increase the number of points in the output polygon.

I understand that it is based on a brilliant algorithm (http://www.antigrain.com/research/adaptive_bezier/index.html) that matches the degree of quality with the original shape, however I am then manipulating the points, so I would like to be able to define a level of quality.

Thanks a lot in advance!

Backbone Events

A little background first if you don't mind... this past year, I was working on a large project where I refactored an entire event system in the largest (proprietary) JavaScript library I've ever seen. In my research I looked at performance, usability, and standard practices. After many long debates, and countless examples, and more debates, Backbone Events came out as the winner.

What I actually preferred though, is making some changes to Backbone Events, because I thought there were a few optimizations that could be done to make it a little better for high performance rendering. Nobody on my team objected then, as long as a changelist was tracked in the events file.

This all being said, would you consider doing this for two.js?

One example of an optimization I made was not calling eventsApi from within trigger, basically allowing to only dispatch 1 event at a time. This was appropriate because triggering simultaneous events is not common enough to compensate the overhead, trigger should remain the fastest method of all if you plan to trigger events at 60fps or more.

Anyway, just curious of your thoughts here, thanks!

Two.js is not competible with Node, or Browserify exactly

I'm a fan of Node.js and I want to package twojs in my code with Browserify.
I tried to place the file build/two.js with a new generated package.json, then require it in a script.
Well, seems it doesn't work.. the _ object behaves strangely..

I found such code like this:
https://github.com/jonobr1/two.js/blob/master/src/two.js#L1304-L1310

  //exports to multiple environments
  if (typeof define === 'function' && define.amd)
  //AMD
  define(function(){ return Two; });
  else if (typeof module != "undefined" && module.exports)
  //Node
  module.exports = Two;

It says in the comments that CommonJS style is supported, I guess.
But it's broken.

Speed down

There is anyway to speed down the animation it goes to fast, i want it slower, but i cant do it

Adding Colour Options

It would be great to have some more colour options.

For the polygons, two tone gradients would be pretty sweet.

Global (or even localised to a polygon) blend modes. I'm guessing implementing the full canvas blendMode set would hit performance hard (ala emulation) but maybe the webgl specific ones? Playing around, I was only able to get 'screen' up and running.

(hi jono!)

SVG interpreter

When I import SVGs using the two.interpret, as in the two.js example, the polygon fill is set to #fff. Is this always the case?

Also, I noted that when round holes are imported (using two.interpret) they seem to be missing the closing anchor in the polygon. For rectangular holes the import works fine.

'On top' functions

I'm working on a map where elements will sometimes superimpose each others.
The three group method used in the sun exemple isn't always appropriate.

it could be easly done by placing a function in the Shape prototype doing
DOMEelement.parentNode.appendChild(DOMElement);

and maybe implement a 'on bottom' function ...

Contribute Example?

Hi,
I've been exploring two.js and created an example bar chart (cause we need more js bar charts right? :P ). It could use some work and I dont know if I'll work on it anymore. Anywho, maybe you can use it as an example . Here it is http://jsfiddle.net/h2sRC/

make Two.js work with cocoon.js

Hi Jono!

First of all thank you for the excellebt library, exactly what i needed (webgl renderer for performance + vector graphic support, bc im gonna use a lot of SVG paths).
Im trying to use two.js with cocoonjs but im experimenting some problems.

You can see on the two screenshot (2x zoom) the difference between the two circles
two

i have tried

var elem = document.body; var params = { type: Two.Types.webgl, fullscreen:true };

var two = new Two(params).appendTo(elem);
console.log(two);
two.antialias = true;

but it did not help.

Im trying to implement a drag system, but if i drag the blue square i have this issue:
screenshot

If i change the Two.Types to canvas it works as expected.

Is there any official support forum/ google group for two.js?

Here is the whole code:

<script src = "libs/two.js"></script>
    <style>
        body{
            background: black;
        }
    </style>
    <script>
    // Make an instance of two and place it on the page.
    var elem = document.body;
    var params = { type: Two.Types.webgl, fullscreen:true };
    var two = new Two(params).appendTo(elem);

    console.log(two);
    two.antialias = true;
    // two has convenience methods to create shapes.
    var circle = two.makeCircle(72, 100, 50);
    var rect = two.makeRectangle(213, 100, 100, 100);

    // The object returned has many stylable properties:
    circle.fill = '#FF8000';
    circle.stroke = 'red'; // Accepts all valid css color
    circle.linewidth = 5;

    rect.fill = 'rgb(0, 200, 255)';
    //rect.opacity = 0.75;
    rect.noStroke();

    // Don't forget to tell two to render everything
    // to the screen


    two.play();


    function pan(deltaX, deltaY){

        rect.translation.x += deltaX;
        rect.translation.y += deltaY;


    }

    var vmousedown = false;
    var mouseX, mouseY;
    var deltaX_old = 0;
    var deltaY_old = 0;
    var deltaX,deltaY;

    elem.addEventListener("touchstart", function(ev)
    {
        vmousedown = true;
        mouseX = ev.touches[0].pageX;
        mouseY = ev.touches[0].pageY;

    });

    elem.addEventListener("touchmove", function(ev)
    {
        deltaX = ev.touches[0].pageX - mouseX - deltaX_old;
        deltaY = ev.touches[0].pageY - mouseY - deltaY_old;

        pan(deltaX,deltaY);

        deltaX_old = ev.touches[0].pageX - mouseX; 
        deltaY_old = ev.touches[0].pageY - mouseY;
    }); 

    elem.addEventListener("touchend", function(ev)
    {
        deltaX_old = 0;
        deltaY_old = 0;

    });             

    </script>
</body>

Is there a simple method to animate strokes?

Hi,
To begin many thanks for your work on Two.js.

I want to use your plugin to draw a simple opened polygone and animate his strokes.

I analyzed the Fresh example to understand how can i do it, but unfortunately without results, googled and stackoverflowed about this with no results too.

Is there a simple way to do this?

My very crappy try : http://avant-garde.io/line/index.html
The visual result i try to reach but without a SVG file : http://avant-garde.io/line/index_o.html

I hope my question is not too silly for you, it's my first post on Github
and sorry for my poor english.

Laurent

Two.Polygon Width & Height

I noticed there's a point in the Up for Discussion section of the readme mentioning a width and height for polygon objects. Personally, that'd be invaluable. Hope it's still under consideration :)

Non-uniform scaling

The ability to scale objects non-uniformly would be a great addition, I believe this can be done by matrix transformations.

Questions: Z-Index, changing circle radius, animate between different polygons, and text and image support?

I'm considering using Two.js in a library I'm making, what I've seen so far looks very good, but I have a few questions:

  1. How do I set the z-index of polygons?

  2. How do I change the radius of a circle? I have some code that uses tween.js to tween/animate a bunch of values, one of those values representing an objects radius, so it goes perhaps from 10 to 20 in steps like 10, 10.5, 11, 11.5, etc. And I need to let two.js use those numbers to change the circles radius, something like:

    • New tween frame with new radius value
    • Change a two.js circle radius using said value
    • two.update()

    How would I go about doing that?

  3. Is it possible to easily animate between any two polygons in two.js or at all? E.x. from a rect to a circle and a circle to a rect, or a complex 4 sided polygon to a 7 sided polygon?

  4. What's the state of Text and Image support in two.js, is it being developed and is there any predictable time-frame for its release?

Anyway, looking forward to playing around with it more and follow its development, looks sweet!

Add a VML renderer for IE<9

It would be nice to support IE<9 with VML. Raphael.js source will probably be useful.

PS: very nice work I was just looking for that some days ago (ended up using three.js for 2D stuff wich is a bit cumbersome).

Adding Colour Options

It would be great to have some more colour options.

For the polygons, two tone gradients would be pretty sweet.

Global (or even localised to a polygon) blend modes. I'm guessing implementing the full canvas blendMode set would hit performance hard (ala emulation) but maybe the webgl specific ones? Playing around, I was only able to get 'screen' up and running.

(hi jono!)

two.js and npm

Hi @jonobr1, guys,

First of all thank you for the awesome library! I'm trying to use two.js with node-canvas, but there are several problems.

  • Older version 0.2.0 is published on npm
  • requiring latest two.js from node complaints about missing dependencies (like _ or requestAnimationFrame).

Just curious, are you planning on adding support for node users?

Thank you!

Almost perfect for AngularJS

Two would make a great component for AngularJS. I'm not sure why Two is using only Backbone for something AngularJS can easily do. I'm using AngularJS and do not need the extra weight of Backbone in my project.

Would it not be possible to swap out Backbone for AngularJS and work with the AngularJS team on this? Especially, seeing that both Two and AngularJS are Google projects!

Safari and Canvas?

Hey guys,

Running a few small tests for something I'm working on. I am by no means a great (or even good) JavaScript dev, and I have a general question about an issue I've found.

Check out this little test: http://jsfiddle.net/5UTAX/11/

I'm drawing a basic Voronoi diagram. It performs quite well in Chrome (26.x) in OS X 10.8.3, with expected slowdowns with more and more polygons. But as soon as I jump into Safari (6.x), the whole thing slows down / crashes around a dozen polygons.

I'm really not sure if it's my implementation or two.js that's the culprit here. Any comments / guidance is much appreciated. Please excuse my crappy code - and I'm absolutely loving the library, keep up the great work!

S

Support for Path and Detection

Does Two support Path objects?

I need the ability to load a SVG data string only and stamp it out then to be able to detect if the pointer is in a given path object. The Fabric.js library features Path operations and apparently Path objects and detection also coming to Canvas v5.

http://kangax.github.io/jstests/canvas-v5

Broken remove on two

Adding

two.remove(circle);

on line 15 of the first example and pressing enter couple times breaks havoc (rectangle is rendered without fill and on each redraw the scene is shifted to the right).

Secondly, is there any way to completely wipe Two's instance and start anew? Unfortunately, now Two is unusable in situations when I want to draw dynamically, different objects into the same location. Or something like two.clear().

Resemble.js update

Hello, and first off, very nice lib, great job! Just came across it today, and I'm really curious to see (or make) some benchmarks, and compatibilities with platforms like Ejecta, CocoonJS, and Windows devices.

But on to the point of this issue... I noticed you are using Resemble.js for testing, and canvas2Blob on top of it. I made a contribution a little while ago that should allow you to just use toDataURL() and drop canvas2Blob for this. If it's the only place you are using it, then entirely.

See here: rsmbl/Resemble.js@40f5314

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.