Giter Club home page Giter Club logo

party-js's Introduction

InstallationUsageContributing

npm GitHub Repo stars GitHub Build Status GitHub Docs Status npm downloads

Installation

The library is written in TypeScript and compiled to an UMD module to allow integration into different environments.

Browsers

You can grab the latest version from jsdelivr.

<script src="https://cdn.jsdelivr.net/npm/party-js@latest/bundle/party.min.js"></script>

The library instance is loaded into the global party object.

Node.JS

If you are using a package-managed environment, you can also install the latest version via npm.

npm install party-js
# or
yarn add party-js

To use it, simply require or import it.

import party from "party-js";
// or
const party = require("party-js");

Usage

The library essentially offers a fully customizeable particle-system implementation into HTML documents. Users of the library have the ability to create and fine-tune effects to their individual liking. The library offers a few simple effects right out-of-the-box, so you don't have to waste time re-creating simple effects.

document.querySelector(".button").addEventListener("click", function (e) {
    party.confetti(this, {
        count: party.variation.range(20, 40),
    });
});

If you want to learn more, check out the quick start guide!

Known Issues

  • "The particles are getting cut off inside the screen!"
    When creating the particle container, the library calculates the document <body>'s size once. If your document size changes during the lifetime of your application you can either:

    1. Remove the #party-js-container. This forces the library to re-initialize the container and will re-calculate the size. All particles will remain in memory, so nothing will be lost.
    2. Manually calculate the needed container size and update it yourself. The library does not do this on a per-frame basis, in order not to unvoluntarily slow down older devices with timeout polling, and watching for document size changes is an expensive task, as of writing.

Contributing

First of all, thank you so much for wanting to contribute to the project! ❤
Please refer to the contribution guidelines when opening issues or creating pull requests.

party-js's People

Contributors

daikiojm avatar gesi avatar ghiculescu avatar swarag-n avatar theghost1980 avatar yiliansource 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

party-js's Issues

Support for mobile?

Hey, is there support for mobile browsers too? I've been trying ontouchstart="party.confetti(this)" onclick="party.confetti(this)" and it is not working.

party.confetti does not work in Angular

Describe the bug
party.confetti does not work in Angular. I try to install the library by download from jsdelivr and install from package.json and the results is the same.
When I install the library by download from jsdelivr, if I get party object in debug mode just after download the library, I see confetti function, but not when I use in any component.

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://stackblitz.com/edit/angular-test-party?file=src%2Fapp%2Fapp.component.ts
  2. Click on click me!
  3. party.confetti does not work but party.screen does

Expected behavior
both party.confetti and party.screen work.

Enviroment

  • Browser
  • Node.js
  • [ X ] Angular 9 / 11

Additional context

Weird footer.

Not a huge problem that I have here, it is just something which could be improved or fixed on the party.js [website]

image

The centering of the "More, GitHub" on the footer is strange. It is neither centered nor is it aligned to a side

The fix I'd like to see for this would be aligning it to the right.

An alternative fix that would also work is centering it, though imo aligning it to the right would look cooler 😄

How to further control the lifetime and speed?

Hi, great lib!

I'd like to have the sparkles appear fast and then stay on screen, or at least for a minute or two.

I've tried tweaking speed, lifetime, messing with modules and creating a custom template, but I could not get the effect I'm after. See CodePen

Is it possible to expose the lifetime and speed within the modules? Or set an easing curve to those values so that they are not constant?

See here what I am trying to achieve:

Thank you

Particles relative to document

Is your feature request related to a problem? Please describe.
Currently the particles are rendered relative to the screen. It would be more intuitive to render them relative to the document instead.

Describe the solution you'd like
The renderer should take the current scroll position into account when rendering particles (this was the default in v1).

For completeness, this behaviour should be customizeable via an option.

Add Quick Start guide to website

Description

Using the library is currently only roughly outlined in the project's README.

Suggested implementation

A quick start guide on the project's website would feel more natural, and could be decorated with interactive examples.

Provide default shapes.

Beyond the simple square and rectangle that are currently implemented, additional default shapes could be provided, such as circles, ellipses, rounded rectangles, etc.

Since those are not high in complexity they could just be stored in the shapes array initially, without having to load anything or having to call an explicit method.

Documentation for custom image emittion

I found out that party.js could emit custom images and data, however, I didn't find much from the documentation. Documenting it (including examples) would do a lot.

Effect Builder

To allow better testing than the samples/, and visually build own effects, it could be useful to have a visual builder integrated into the documentation site. The style should be similar to the interactive examples seen on Framer: Motion.

image

Features

  • Tweaking of all emitter-related properties via an intuitive, visual editor (see required properties).
  • Code-generation of the configured properties.

Required properties

Emitter Options

Label Type
Duration number
Loops number
Use gravity? boolean
Max. particles number
Modules Module[]

Emission Options

Label Type
Rate number
Bursts Burst[]
Source HTMLElement
Angle Variation<number>
Lifetime Variation<number>
Speed Variation<number>
Size Variation<number>
Rotation Variation<Vector>
Color Variation<Color>

Render Options

Label Type
Shape Shape
Use lighting? boolean

Required field types

Constructed from the properties above.

  • boolean
  • number, Variation<number>
  • Vector, Variation<Vector>
  • Array<T>
  • HTMLElement
  • Burst
  • Module

Dynamic importing of party-js

Guess I'm doing something wrong here, but why do I need to do this module.default.default thing to get a dynamic import to work? (This is Sveltekit code)

    onMount(async () => {
        if (confetti && browser) {
            const module = await import("party-js");
            const party = module.default.default;
            
            party.confetti(el, {
                count: party.variation.range(20, 40),
            });
        }
    });

How to define custom colors in the jsdelivr version?

Hi there and congratulations for this awesome library!

I tried unlimited ways to define custom colors in the jsdelivr version without luck.

I tried to use plain text, integers, looking any of the properties of the "party" object, but I did not found any way to define custom colors...

Could you add some samples about how to customize the colors of the effects?

Documentation sandbox/playground

Is your feature request related to a problem? Please describe.
It's a bother if you want to quickly try out the library and have to go through the proper setup process. It would be nice to be able to try out the basic functionality of the library live on the page.

Describe the solution you'd like
A sandbox environment, where users can freely try out certain effects and write code themselves, preferrably with added IntelliSense.


  • Text Editor: The text editor should be built using CodeMirror, to allow for flexibility and the usage of their powerful addons.
  • Autocompletion: Refer to the demo for an example. This should aid users in development.
  • Load Samples: It should be possible to load some samples into the sandbox (for example the three examples featured on the homepage).
  • Save/Load: It should be possible to save written sandbox code to the URL with Ctrl+S. Opening that URL should produce the same code. This can be used to share built effects with others.
  • Test Button: A button should exist with which the sandbox code can be tested. this should be set to the button, while event should be set to the click event of the button.

Respect the 'prefers-reduced-motion' media query

Is your feature request related to a problem? Please describe.
The media query in question is intended to remove unnecessary motion in the DOM, which is essentially what the library provides.

Describe the solution you'd like
By default, the library should disable particles if this media query is disabled. This should additionally be controllable via a setting respectReducedMotion, which defaults to true.

The check can be performed via:

if (window.matchMedia('(prefers-reduced-motion)').matches) { /* ... */ }

Improve Source specification

Is your feature request related to a problem? Please describe.
Currently a Source can be specified as a Rect, HTMLElement or MouseEvent. This works for rectangular areas and points, but is not extendible to differently shaped areas.

Describe the solution you'd like
An idea could be an EmitterSource interface, which implements a GetSample() method, that returns a random point where a particle should be emitted from. However, this would result in a lot of files, cluttering up the project, taking up a lot of space.

Another idea is a builder-pattern-like implementation, where an element in the chain automatically infers the source needed.

// Define the type that will be used for sampling from sources.
interface SourceSampler {
    getSample(): Vector;
}

// Example dynamic usage: The element can be a Rect, Circle, HTMLElement or MouseEvent.
sourceSampler().dynamic(element);

// Example custom usage: The developer provides their own sampling method.
sourceSampler().custom(() => new party.Vector(1, 2, 3));

jsdelivr release

Once the v2 features (#19) are sufficiently implemented, the library should offer a jsdelivr release, which should be automatically generated via a GitHub Action.

NPM

add to npm

Ability to control "range" (radius)

Is your feature request related to a problem? Please describe.

In the party.sparkles() I can control size, count, etc. But I can't control the range at which how far the stars go from the epicenter. It would be nice to have a configuration for that.

Describe the solution you'd like

Perhaps

party.sparkles(target, {radius: party.variation.range(100, 150) })

Add emitter unit tests

Is your feature request related to a problem? Please describe.
Its hard to be sure if the emitter functions precisely as intended currently. The effects caused by it have to be eyeballed.

Describe the solution you'd like
Proper coverage of the emitter class using unit tests. Since it's functionality is time (tick) based, some tolerance can be applied.

[BUG] getBoundingClientRect is not a method

While using party.element, it runs the following code:

element: function (element, options) {
    options = options || {};
    overrideUndefinedOptions(options, {
    shape: party.array(["square", "rectangle"]),
    count: party.variation(40, 0.5),
    spread: party.constant(80),
    size: party.variation(10, 0.8),
    velocity: party.variation(-300, 1),
    angularVelocity: party.minmax(1, 6)
});
this.area(element.getBoundingClientRect(), options);

from line 869 to 879

However, the method element.getBoundingCLientRect does not exist anywhere within the file except for that one call:

image

Because of this, it throws an exception and fails to execute.

`party-js-container` div is too small, confetti effects are cut off.

I'm using the confetti effect on my website for some buttons and when a key is pressed, but I've noticed that the confetti only goes so far into my page before being cut off. It looks like the party-js-container div might be at fault here, as it only covers part of my page.
Screen Shot 2021-08-30 at 3 40 36 PM

Here's an example of what it looks like:

confetti-example.mp4

As you can see, the confetti gets cut off halfway through.

This issue does not seem to happen in version 2.0.0. In my experience, the party-js-container takes up the entire page in that version.

Thanks!

Write up documentation for the project

Description

This does not refer to the documentation of the JavaScript code, which is already largely in place, but rather the addition of docs to the project website. These should allow a more detailed and in-depth understanding of the project, especially regarding the available configuration.

Online demos

Is your feature request related to a problem? Please describe.
There is no way to test the library, there is no real demo that shows how it looks like, it requires cloning the repo to see how it works.

Describe the solution you'd like
Publish samples on the website so users can see how the library works.

Describe alternatives you've considered
I've searched and was not able to find any demo, I don't want to clone the repo to see how it works.

Add more patterns.

Add more patterns, such as random direction, or confetti from the sides, etc.

A demo of what I mean can be found here

Support complex shapes instead of only quads

Description

Currently party.js only supports the rendering of quads, although those can be translated, rotated and scaled. Regarding the potential desire for shapes that go beyond simple quads, it would be an idea to allow the rendering of more complex shapes, like circles, hearts, stars, et cetera.

Suggested implementation

In order to apply transforms to particles, their shapes are defined as points denoting a polygon. However, the points that make up this polygon can be modified freely, with the quad being the current default.

A user-friendly implementation would be to let the user define particle shapes himself using SVG paths, with square or rectangle being the default fallback.

party.registerShape('star', '<polygon points="512,197.816 325.961,185.585 255.898,9.569 185.835,185.585 0,197.816 142.534,318.842 95.762,502.431 255.898,401.21 416.035,502.431 369.263,318.842"/>');

This shape could then be stored in a lookup, and provided to a particle spawning method via the options object.

party.cursor({ shape: 'star' });

The parsing of the SVG could be done with a DOMParser, parsing the XML structure and reading the required data.

See also:

Additional thoughts

Shape centering

When registering a shape without an SVG ViewBox, the center of the graphic cannot be guaranteed. The best option here would probably be to calculate the bounding box of the shape during registration, and use this as a sort of "dummy ViewBox".

Path support

Once imported polygons are supported, the next step could be to support SVG paths entirely. Bezier curves can be drawn using context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);. The exact procedure would have to be parsed from the SVG path object.

To follow the single-responsibility-principle, these paths should not be implemented using the current Polygon() method, but rather using its own method (e.g. Path()), with the appropriate draw() method.

Performance

Since every point needs to be transformed, the more points (vertices) a polygon has, the larger the performance impact. This will cause performance to drop much faster than with the current quad renderings.

Add migration guide to docs (v1 -> v2)

Is your feature request related to a problem? Please describe.
If people previously used v1 of the library, they potentially do not know how to migrate to v2.

Describe the solution you'd like
An extra chapter in the documentation describing how to achieve the migration.

Library rewrite

Description

With party.js already having a good foundation and seemingly being enjoyed for projects, it's time to give the project a better roadmap ahead. The initial idea was to have the, already implemented, particle effects, with a large focus on customizeability. Now seems like a good opportunity to build on that idea and add new features.

Points of focus

  • The library will be re-written in TypeScript. This is meant to assist in the development process, as well as to ease developer intentions to integrate the library into their projects by providing intuitive type declarations via Intellisense.
  • Customizeability is still key. In v1 this was a huge strength of the library. This strength is in no way to be discarded.
  • Performance matters. Even with new features being implemented, the library should still try it's hardest to run smoothly under reasonable amounts of stress in a production environment.

Further concepts will be discussed in subsequent issues.

Editable codeblocks in the documentation

Is your feature request related to a problem? Please describe.
The current preview codeblocks in the docs are nice, but usually their internal code differs from what's actually shown, and users cannot play around with the code themselves.

image

Describe the solution you'd like
The solution could be a "live codeblock" (similar to the react-live-examples), that allows users to Copy and Run code. A certain set of variables (like party, the clickEvent and the runButton) would need to be exposed to the code.

'import party from "party-js"' not working in TypeScript

Describe the bug

This does NOT work:

import "./styles.css";
import party from "party-js";
// const party = require("party-js");

export default function App() {
  return (
    <div className="App">
      <h1 onClick={(e) => party.confetti(e.target)}>Party!</h1>
    </div>
  );
}

This WORKS:

import "./styles.css";
// import party from "party-js";
const party = require("party-js");

export default function App() {
  return (
    <div className="App">
      <h1 onClick={(e) => party.confetti(e.target)}>Party!</h1>
    </div>
  );
}

The error you get is:

TypeError
can't access property "confetti", _partyJs.default is undefined

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/nostalgic-breeze-s5uwv?file=/src/App.tsx
  2. Click on the H1 heading
  3. See error

Expected behavior
An error shouldn't happen. :)

Note, if you change the import to const party = require("party-js"); instead, then it works.

But if I do that my eslint is barking at me. :)

error  Require statement not part of import statement  @typescript-eslint/no-var-requires

Enviroment

  • Browser
  • Node.js
  • Other

Additional context

Test and experiment on: https://codesandbox.io/s/nostalgic-breeze-s5uwv?file=/src/App.tsx:56-90

My project where this came up was a Preact-cli TypeScript app but the above sandbox fully demonstrates it too.

Problems when used as npm package

Hey there,

first of all thanks for your work! I am currently using your libary in Vuejs. But to include it there was really annoying. You are providing an NPM (The Node.js packet manager) package. But there is no export in your script. So in my opinion it is not usable as NPM package. Please consider doing something like:

export default party

at the end of your file to enable easy import with something like

import party from 'party-js'.

Thank you in advance!

More than an issue it may be a Suggestion to improve something I need to use and maybe others like me.

Hi there @yiliansource first of all I hope you may be great. I really like the library. It is a great asset.

Right now I'm working in a website and I would like to use it, in order to "celebrate the new users whom joined the NewsLetter".

The issue I'm having is: I cannot set the z-index property for the animation.

I have tried modifying the parent element's z-index property. For example, this is the jsx code while using react & gatsby:

<div className="coloredScreenBGFixed">
       <div className="subcriptionCont" id="confettyDiv">
             ...some other elements
             and here below the button to test the library by executing the click event:
             <div id="my-button"  onClick={() => party.screen()}>
                   Click me!
             </div>
       </div>
</div>

The CSS file shows the properties z-index of all parent's as:
z-index: '99999'
Because I use the descendant way in all my websites to maintain order.
Which means I set 99999 for the element to be on top, and all the rest 99990, 99980...you get the point for sure.

I can see the particles are emitted only on the same z-index = 0. I have done some tests and if I set all the divs to a z-index = 0, the particles show on top which is fine.

The problem is
what happen if I need to render the confetti on top of everything?
I have set the parent for this div as absolute with z-index: 99999(my higher value), but I cannot find a way to set the confetti to be on top of that, in fact so far I wasn't able to find any way to set this property at all.
Could be possible to add this feature? Ot let me know how could I solve this in order to be able to set the z-index property of the animation itself. The code inside of party.min.js is kind of heavy to modify also when someone doesn't knows it.

If you let me and tell me how? I could modify the property and help you out by issuing a pull request?

Maybe other people can find this useful when they need to render on top of the body or something else?

Please let me know I have explained myself or If you need more info. I would really appreciate the help so I can use the library. Thanks.

A pic from this in action: Click to see how the particles stay on the lower z-index

Documentation examples/demos

Is your feature request related to a problem? Please describe.
Currently the v2 documentation does not feature any examples on how the library looks in action. This makes it hard to get an idea of how to implement certain effects, and what they will look like.

Describe the solution you'd like
A subcategory of the documentation with samples. They could include:

  • Particles on button click
  • Confetti on drag (hold)
  • Custom SVG particles
  • (more to come...?)

Feel free to suggest more desired examples!

Improve particle emission

Is your feature request related to a problem? Please describe.
There are a couple of shortcomings with the current system:

  • By default the loop count is -1, which results in infinity. There more common usecase is a single iteration though, which should be 1.
  • Once an emitters duration and loop count is over, it is destroyed. If particles are still active however, they are removed, even if they would still be alive. A solution would be to keep the emitter alive until the loop count and duration is exceeded AND all particles are despawned.
  • Currently there is no way to clear particles easily. Scenes and emitters should offer a clearParticles method for convenience.

Improve Module specification

Is your feature request related to a problem? Please describe.
Adding new modules to emitters is a bit janky, and there are a lot of cluttered module files that basically all do the same.

Describe the solution you'd like
Instead of having a lot of module classes that function similarly, we could generate modules through a builder, where users can, through chaining, specify the driven property, the value and what it's driven by (lifetime/size).

Example

new ModuleBuilder()
    .drive("size")
    .by((t) => t * 2)
    .through("lifetime")
    .build();

Architectural improvements and features leading up to v2

Is your feature request related to a problem? Please describe.
Since the pre-release some points have come or have been made that could be improved using some architectural changes. Additionally, some "missing" features need to be implemented aswell.

Architecture

  • Remove ShapeOptions and place them into EmissionOptions.
  • Place the particle-related EmitterOptions into EmissionOptions.
  • Rename RendererOptions to RenderOptions.
  • Allow to properly specify a Source as the emission area of an emitter.
  • Allow a synthetic import syntax (import party from "party-js" as well as import * as party from "party-js") (#48).
  • Rename the Node.js build directory from dist to lib, to indicate that it is a library.
  • Make Rect a proper type.
  • Rename Colour to Color.

Features

  • Add a ColorOverLifetime module.
  • Add a ColorOverSize module.
  • Add an opacity property and a OpacityOverLifetime module.
  • Add a feature to "replace" the party.screen() method (#41).

Implement lazy DOM setup

Is your feature request related to a problem? Please describe.
Currently it is not possible to import the library into SSR applications, since the setup immediately takes place when imported.

Describe the solution you'd like
A lazy setup instead of an immediate one, similar to how the DOM containers in the library behave. The effects aren't really renderable via SSR, but as long as no methods are called at server rendering time, it can still be imported and used in client side code.

v2.0.0 now places the party in the upper left-hand corner

Describe the bug
The sparkles (or confetti) are now in the upper left-hand corner of the page.

Screen Shot 2021-05-13 at 8 19 52 AM

Here's how I run it:

<input
  onClick={(event) => {
    event.stopPropagation();
    if (true) {
      party.sparkles(event.target as HTMLElement, {
      });
    }
  }}
/>{

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/cool-paper-9urhf?file=/src/App.tsx

Expected behavior
A clear and concise description of what you expected to happen.

Enviroment

  • Browser
  • Node.js
  • Other

Additional context

v2.0.0 just came out.

Missing Meta Description

Describe the bug

The meta description in the embed produced by any links to the homepage are the default description still.

To Reproduce

Steps to reproduce the behavior:

  1. Paste the link into any chat service, such as Discord or Guilded
  2. See error

Expected behavior

Your own description of your amazing project!

Additional context

This is how it currently looks:
image

You'll find the place to change it here:

description="Description will go into a meta tag in <head />"

Support tree shaking

The library could save some bundled size by supporting tree shaking. This will have to be looked into.

Color gradient randomization

Description

Since numeric values can already be randomized, a helper class for color gradient randomization, i.e. a wrapper to pick a random color from a specified gradient would be great.

Suggested implementation

This could also clean up the currently global mix(color1, color2) and the hslToRgb(h, s, l) methods, by creating a new class for the color.

Then, like with the other randomization options, a public method called linearGradient could be introduced, getting colors passed in 6-digit-hex format.

{ color: party.linearGradient('#000000', '#ffffff') }

The implementation could then pick a random point on the gradient and sample the color from there.

Randomization configuration.

Description

The current method of randomizing options is a bit flawed and messy.
Certain options have randomization implemented, in various ways.

Suggested implementation

Instead of having the randomization implemented as multiple options (i.e. option and optionVariation), we could create objects that hold the randomization that is desired.

Note that the specified randomizations should not be applied during creation, but should be written in a generic way so multiple created particles can all have different resulting options.

A list of possible randomization options could include:

Constant

A value of any type. Just returns the constant value, no randomization, no variation.
(Can also be created via party.constant(value), but this will only return the passed value.)

Variation

Only numeric values allowed. Creation is done via party.variation(value, variation, [isRelative = true]).
Either uses the applyRelativeVariation or applyAbsoluteVariation.

MinMaxSpan

Only numeric values allowed. Creation is one via party.minmax(min, max).
Generates a random value between min and max.

Array

Returns a random element from the specified array.
(Can also be created via party.array(array), but this will only return the passed array.)

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.