Code Monkey home page Code Monkey logo

pts's Introduction

Pts

image

Pts is a typescript/javascript library for visualization and creative-coding.

Get started at ptsjs.org.

Please give it a try, file issues, and send feedbacks to @williamngan. Thank you!


Usage

Option 1
Get the latest pts.js or pts.min.js (in dist folder). Alternatively use a CDN service like cdnjs or jsdelivr or unpkg. Then add it to your html page like this:

<script type="text/javascript" src="path/to/pts.js"></script>

Pts is pretty lightweight. Currently at ~100kb minified and 30kb gzipped.

Option 2:
Install via npm install pts. Then you can choose to import some parts of Pts into your project as needed.

import {CanvasSpace, Pt, Group, Line} from 'pts';

To quickly get started, try download or clone these repos:

Get Started
Read the guides and take a look at the demos and their source code.
If you need help, please don't hesitate to file an issue.


For development

Pts is written in typescript. You can clone or fork this project and build it as follows:

Build and test

Clone this repo and install dependencies via npm install.

npm start
npm run build
npm test

Generate documentations

Run this to generate Pts styled documentations. (Requires python 3.6)

npm run docs 

If you prefer to generate default typedocs, run this:

typedoc --readme none --out typedocs src --name Pts

Contributing

We appreciate your support and feedbacks!

Please file issues if you find bugs and have feature requests. If you are able to send small PRs to improve Pts or fix bugs, that would be awesome too.

For larger PRs, please ping @williamngan to discuss first.


License

Apache License 2.0. See LICENSE file for details.
Copyright ยฉ 2017-today by William Ngan and contributors.

pts's People

Contributors

albizures avatar alexander-welshtein avatar amilajack avatar andrzejchmura avatar bnjm avatar bsouthga avatar carlo-colombo avatar dependabot[bot] avatar doseofted avatar kijowski avatar prkirby avatar rmschindler avatar romgrk avatar sandstrom avatar thewarpaint avatar tibotiber avatar tom-bywild avatar williamngan avatar yvee1 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

pts's Issues

Circle.fromTriangle function

Add a Circle.fromTriangle function to create a circle from 3 points.

Something like:

Circle.fromTriangle( pts:GroupLike, asCircumcircle:boolean ): Group

which maps to Triangle.circumcircle and Triangle.incircle respectively.

physics particles resize

Hi. I have an issue with physics particles resize. Example: https://ptsjs.org/demo/?name=physics.particles.

When i refresh page on small size and then do big screen size, canvas has changed width but space with circles stay remains the same as it was before resizing to big screen.
Why resize doesn't work? Help me to fix this issue please.

screen-1

screen-2

Remove particle by id

Thanks your work. I'm having a lot of fun with the library :)

I found the need to remove an specific particle that I'm keeping track by its id.

When I add the particle world.add(particle, id)
I can later access it with world.particle(id)

Removing the particle though, it only can be done by its world's index.

My current around is setting the particle id particle.id = id, and then I iterate over all world particles to find its index:

getParticleIndex(id) {
        for (let index = 0; index < world.particleCount; index++) {
            if (world.particle(index).id === id) {
                return index
            }
        }
        return -1
    }

Following the style of world.add() it seems that it would make sense that world.remove() could be used by an id as well.

drop is triggered on mouse up even if no drag

Hi @williamngan, this is a very amazing lib you've created there. Thanks a bunch :).

It seems that the UIDragger triggers drop events on mouse up even when there has been no dragging. Let me know if this is not clear enough.

I'm gonna push a PR with a suggested fix which I tested for my usage. Hope it can help.

UIDragger onDrop called twice

Hi @williamngan,

A bit in the style of #61 but different.

My onDrop handler gets called twice every time a drop event happens. I looked at stack traces and it is called on one side by the UIDragger logic in UI.ts L446, and on the other side by the listen handler in UI.ts L174 because I called UI.track() for all event types on my UIDragger.

For the moment, I get around the issue by tracking all events except drop, but I was wondering if you think there is a better behavior we could imagine for this case. I think it would be a fairly frequent use-case and quite confusing to understand what happens. I'm willing to make the changes required if I understand what you think would be a good solution (if any) and how to implement it.

Thanks again for the great work on pts.

Metronome.start() is called more than once when starting an animation

It looks like when you use a Tempo object to keep time, it calls start multiple times with the same count for steps 0 and 1.

Here's some code to reproduce - assumes you've got a space defined somewhere.

const tempo = new Tempo(120);
tempo.every(2).start((count) => {
    console.log('on start: ', count);
});
space.add(tempo);
space.play()

I'm expecting the start function to be called once every two beats, but instead, I'm seeing an 'on start: count' message multiple times per beat. The console.log message is just printing out the same value over and over until the count changes.

Utils.split question

Very cool library! I'm having a blast playing with it and am really admiring the attention to detail and API UX.

I had one question about the Utils.split function. When called like this:

Utils.split([1,2,3], 2, 1, true) // [[1,2],[2,3],[3]]

with loopback set to true, I would expect the last element of the returned array to be [3, 1], NOT [3]. Is this an accurate expectation on my end? Or am I misunderstanding something?

Pts.version

Any chance you could make a Pts.version() method or Pts.version property

UI is not exported in some files

I note that the experimental module UI.js is not exported from dist/es2015/_module.js and dist/es2015/_lib.js. Is there any specific reason for that? If developers want to use it, they have to export UI in these files.

Bound class duplicate

I am using angular 6 and try to use the library by installing it using npm.
I recieved this error after importing the Pts.

ERROR in node_modules/pts/dist/pts.d.ts(6,14): error TS2300: Duplicate identifier 'Bound'.
node_modules/pts/dist/pts.d.ts(743,14): error TS2300: Duplicate identifier 'Bound'.

Quick observations about script tags

Quick observation: When using the following script tag
<script src="https://unpkg.com/pts/dist/pts.min.js"></script>

This line is not working

space.playOnce(200).bindMouse().bindTouch();

but this works

space.bindMouse().bindTouch().play();

So all is good.

When using this script tag mentioned in Getting Started

<script src="https://raw.githubusercontent.com/williamngan/pts/master/dist/pts.js"></script>

I get this error:

Refused to execute script from 'https://raw.githubusercontent.com/williamngan/pts/master/dist/pts.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.

and can't do much with it.

All is good since the other tags works.

space.getForm is not a function

Using pts via npm.

const space = new CanvasSpace(el);
    space.setup({
      bgcolor: '#ececec',
      resize: true,
      retina: true
    });
    const form = space.getForm();

getForm is not currently a method on the space object. Returning undefined.

Drawing after initial setup of space

I am trying out Pts for graphics on a structural analysis app (using Angular for the frontend). The scene initialises without anything shown, and as the user adds nodes and beams to the structure, I am calling this.space.add() with the new line/pt.

For example:

drawBeam(i: number, j: number) {
    let pti = this.nodes[i-1].pt; 
    let ptj = this.nodes[j-1].pt; 
    
    this.space.add((time, ftime, space) => {
        this.form.line([pti, ptj])
      })
    }

As I understand it, this is creating a new animation callback function for every item added to the scene.

Is this a bad way to structure my code? Is there a better way to add new items to the scene after the initial setup?

Any tips are appreciated!

An easy way to load image

Make it easy to load an image, and to create screen capture.
Potentially provide an iterator/generator to easily go through all pixels in an image.

Sound / music ?

Hi,

This looks awesome. Congrats!

Are you planning to integrate audio/sound generation in any way? I'm intrigued by the idea of mapping the points into sound or music. Any suggestion?

Thanks!

This code cannot be converted from ES6. extending native class: Array

Trying to run this in a Google Closure context (compiling to ES5), I'm running into this error when I install and import it via NPM, then compile it:

Closure compilation failed with 1 errors
--- node_modules/pts/dist/index.js:288
This code cannot be converted from ES6. extending native class: Array

Is there a way that you could provide an ES5-compatible bundle?

Num.cycle hit edge

Your library is great, but when I tried to make a circle go around the Rect edge,
I use Num.cycle to generate interval number, use
if (Num.equals(interval, 1, 0.001)) { console.log("equals"); edge++; if (edge > 3) { edge = 0; } }
to check interval number is near 1,
When interval number nears 1, I'll change the circle edge.
But, Num.cycle numbers always not in control, sometime it's under 1 for times, some times it across it for times.

Is there a best practice to accomplish this target?

Rendering of Curves

I'm curious why the decision in how to render a given curve wasn't left to the Form (all curves are passed into the Form as a line group). For example, since bezier drawing is available natively on both canvas and svg it could be optionally used as an alternative rendering choice in those cases.

Website not working on mobile

Hi

I did not get into investigate why but website and library is not working on the phones
this should not be the case as no technologies are used that modern web browsers on phone do not support or is it?

Alex

UIDragger emits onClick with onDrop

A bit of a follow up to #63.

UIDragger emits both onClick and onDrop when uidrop happens. This is because uidrop comes from the space's up event (UI.ts#L449) which emits onClick (UI.ts#L361). This can be managed in user land (that's what I do so far), but there may be an opportunity for a better behaviour. What are your thoughts on this?

If interested, I can have a go at starting a PR.

Mouse events not firing correctly?

I'm completely befuddled. The demos on the main site and the react example (cloning and running) work just fine, but when I try the first "Getting started" example my own using the latest release my animations are not working at all.

Codepen reproduction: https://codepen.io/lilactown/pen/WKLGea

Strangely, closing and opening the devtools causes the animation to fire?? ๐Ÿ˜–

Confirmed in Chrome 68.0.3440.84 (Official Build) (64-bit) and Firefox 61.0.1 (64-bit).

Why does mouse up after drag and release send the down action type?

I'm not sure if this is a bug, but the current action type implementation for dragging and releasing is not what I would expect, and seems counter intuitive to me. When initiating a drag and then releasing I would expect a sequence of actions to go like this move -> down -> [drag, move...] -> up, however the current implementations gives move -> down -> [drag, move...] -> up -> down. That final down does not make sense to me since at this point the mouse is actually up. Is there a reason for this?

This is the snippet from src that causes the behavior.
`
/**

  • MouseUp handler.
  • @param evt
    */
    protected _mouseUp( evt:MouseEvent|TouchEvent ) {
    this._mouseAction( UIA.up, evt );
    if (this._dragged) this._mouseAction( UIA.down, evt ); <-- hmm?
    this._pressed = false;
    this._dragged = false;
    return false;
    }
    `

You can see how this effects the behavior in the mouse drag demo http://ptsjs.org/demo/edit/?name=canvasspace.action

My expectation would be that if you release while dragging the stretch variable should be set to false and the group of points should immediately start disappearing, however this only happens if you stop moving the mouse and then do a mouse press and release.

Sidequest: Would be convenient to have dragStart and dragEnd events (just say'n :D).

p.s. Love the library, great work!

Keep getting error: Uncaught TypeError: Constructor Float32Array requires 'new'

Hi,

In Chrome, whenever I build with webpack and import pts I am seeing this error:
Uncaught TypeError: Constructor Float32Array requires 'new'

I have read that I need to use babel-plugin-transform-builtin-extend in my .babelrc, however it doesn't seem to help. Can someone post their working .babelrc/webpack babel-loader config?

Thanks!

Missing way to check if a named particle exists

The following example throws an error:

world.removeParticle("non-existing-particle")

Same for this one:

let particle = world.particle("non-existing-particle")

Maybe the previous method should return null if it does not exists.

Alternatively an aditional method could be added

let exists = world.particleExists("non-existing-particle")

:)

resize function override not working

space.add custom resize function causing error?

space.add( {
start: (bound, space) => {
// code for init
},
animate: (time, ftime, space) => {
// code for animation
},
action: (type, x, y, event) => {
// code for interaction
},
resize: (size, event) => {
// code for resize
}
} );

failing to load in Gatsby

Hi, had a great time playing with this beautiful thing on my local develop build of Gatsby and managed to create a cool effect. I was very disappointed to discover that the build failed with the error Error: Constructor Float32Array requires 'new' and nothing I have done has been able to rectify this (including the obvious adding of 'new', playing around with the babel config and even bringing the code inside the project as opposed to being a node module so I had more control over the transpilation.

Of course this is because this is an ES6 module but I can't figure out exactly what I need to do to get it to work. I guess you may not be familiar with Gatsby but could you tell me specifically what babel config needs to be done in order to get this to compile?

Many thanks :)

drag elements instead of drawing at cursor position?

Hello,

Nice library, i have spent all morning trying to learn and find what it has to offer, and while i find it very nice and capable of doing a lot of good work, i cannot find how to perform actions on drag.

Reading the guide i see that there is that thing called players in space that has a drag callback, and also in the docs i see that there is a pointeractions drag property, but for me is unclear how to use those methods to create something simple like for example a drag slider.

Also, could this library be used to retrict the movement or make the illusion of dragging a particle over a line, even if this line is diagonal?

Thanks

Physics in Safari behave slightly different.

I've been playing with Particles demo and I've noticed different behaviour comparing the same example in Safari and other browsers (Chrome & Firefox).

On Chrome, when I hit random particle with the one I have attached to my cursor, it feels like a real collision โ€“ it changes the direction of movement and speed as well. When I do the same action on Safari, the particle kinda sticks to my cursor for a while (not always but most of the time). That behaviour feels definitely less natural.

Here's screen recording of the same demo file.

  • Left is Safari 11.1.2 (13605.3.8)
  • Right is Chrome 68.0.3440.84

Running on macOS HighSierra 10.13.6, MBP Retina.

UIButton onClick event not working

I'm trying to register a mouse click using the following:

const btn = UIButton.fromCircle( [p1, p2] );
btn.onClick( ui => {
    console.log('btn clicked');
});
btn.render( g => form.fillOnly("#000").circle( g ) );

The button renders but nothing appears in console when clicking.

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.