Git Product home page Git Product logo

confetti-js's Introduction

๐ŸŽ‰ Confetti Generator ๐ŸŽ‰

Easily Generate random confetti with javascript and make your design look cooler

Demo ๐Ÿš€

Demo // Examples

Why?

Have you ever seen that cool looking confetti on landing pages and above-the-fold content? We give you the power to create the same effect for free and without the hassle of having to design or code it from scratch.

Installing/Using

๐Ÿ“ฒ Downloading

  • Using npm

      npm install confetti-js --save
  • Direct download -> click here

โž• Add scripts

  • The classic way

    <script src="node_modules/confetti-js/dist/index.min.js"></script>
  • ES6 module

    // At the component you want to use confetti
    import ConfettiGenerator from "confetti-js";

๐Ÿค” How to use it?

After installing the plugin(the topic above), just call-it passing your options:

html

<canvas id="my-canvas"></canvas>

javascript

var confettiSettings = { target: 'my-canvas' };
var confetti = new ConfettiGenerator(confettiSettings);
confetti.render();

You can also pass a canvas element as the target:

var confettiElement = document.getElementById('my-canvas');
var confettiSettings = { target: confettiElement };
var confetti = new ConfettiGenerator(confettiSettings);
confetti.render();

React

React.useEffect(() => {
  const confettiSettings = { target: 'my-canvas' };
  const confetti = new ConfettiGenerator(confettiSettings);
  confetti.render();

  return () => confetti.clear();
}, []) // add the var dependencies or not

done!

Options

Attribute Description Example value Default value
target The Id tag or node of the canvas that will be used 'my-canvas' 'confetti-holder'
max The number of props(confetti) to be rendered 11 80
size Prop size 1.8 1
animate If the confetti should fall false true
respawn If the confetti should be recreated after going off-screen false true
clock The speed confetti fall 50 25
props The type of props(confetti) that should be rendered. In addition to those listed in the default, there's a special "svg" type which requires further configuration and is detailed below. ['circle', 'square'] ['circle', 'square', 'triangle', 'line']
colors The color to be rendered on the confetti. By default, RGB format inside an array. [[0,0,0], [255,255,255]] [[165,104,246],[230,61,135],[0,199,228],[253,214,126]]
start_from_edge Whether the confettis should fall from the top of the screen (or should move up from the bottom) true false
width Canvas width 960 window size
height Canvas height 767 window height
rotate If set to true, SVG and squares will rotate while falling. true false

Special SVG particle type

There is an extra special partical type ("prop") which allows you to render SVGs as confetti particles. For example:

{
  "props": [
    "circle",
    "square",
    { "type": "svg", "src": "site/hat.svg" }
  ]
}

You must specify the type and src properties. There are also a few other configuration properties available to SVG objects:

Attribute Description Example value Default value
size Set the size of the SVG when it renders as a particle. 25 15
weight The probability of this particle being rendered, where 1 is a regular weight, and 0.1 is uncommon. 0.5 1

API

Using the object generated by new ConfettiGenerator() is pretty easy, there're just two main methods actually.

Method Description
render Render the confetti at the config <canvas/>
clear Clear the <canvas/> where the confetti where rendered
var confetti = new ConfettiGenerator();
confetti.render();
//
confetti.clear();

License

You can use/hack/re-distribute/do whatever you want with this for free without having to credit the author or anything. Go on, just do it.

But if you take the time to contribute with the project it would be nice too, just saying :)

Thanks

Special thanks to "Paper Matthew" on codepen for providing the starting point wich I fork to build this. You are awesome.

confetti-js's People

Contributors

agezao avatar danilowoz avatar jonpacker avatar kevingomezdev avatar qortex 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

confetti-js's Issues

Color option is not visually respected

Confetti particles currently appear (visually) to not respect the provided color options. This is because there is no way to control the usage of opacity, which on different colored backgrounds appears to alter the color of the particles.

Here is a link to an example of this reproduced. Judging from the source, it appears that for this specific example the opacity is not intended to apply as it is determined by a randomly assigned radius, something that is not used in rendering square particles. Ideally the opacity would be able to be controlled by an additional option, or at the very least disabled by an option.

Multiple network calls to fetch svg's

I am facing issue with multiple network calls. I have added solution as provided in one of resolved issue. I have added preloaded svg's fix using image src attribute. Now problem is how can same change can be incorporated in production build. On dev environment I did it manually. Would be helpful to know for the production fix

Feature request: Begin falling from top and stop until confetti is over

Hi, thanks for the wonderful and so small library. To make a better visual effect I'm looking for ways to start the animation so the confetti falls from top to bottom instead of start with the whole screen filled. And also a new method, eg stop(), that would stop new confetti so that current confetti keeps falling until no more confetti is on screen.

If that is not clear I can try explaining it better and if you don't think that is useful I can understand and so the issue can be closed ;-)

Using custom SVG props causes multiple requests for the same resource

Hello,

I've recently noticed that using custom SVG confetti particles leads to multiple requests for the same SVG file for every single animation frame. I tested this out on the demo and I'm getting the same issue. This is pretty taxing on the CPU and my fans spin up pretty loud after ๐Ÿ˜…, especially when using multiple custom confetti particles. Is there a fix for this?

How to replicate issue

  1. Visit https://agezao.github.io/confetti-js/
  2. Make sure SVG(hat.svg) is selected in 'Type of confetti' section
  3. Open dev tools, and check the network tab. This is what it looks like on Chrome. The same happens on Safari as well.
    image

Hoping there can be a fix for this soon!
Thanks!

Retina support

The circles are blurry on retina devices/zoomed, is there a way around this?

animate is not working

Hi,

I installed confetti-js in my app (Ionic 4, angular). I put the method render in ngOnInit, the canvas is showing but the animation is not working, This the script:

`
const confettiSettings = {
target: 'confetti-holder',
max: '180',
animate: true,
props: ['circle', 'square', 'triangle', 'line'],
colors: [[165, 104, 246], [230, 61, 135], [0, 199, 228], [253, 214, 126]],
clock: '25'
};

this.confetti = new ConfettiGenerator(confettiSettings);

this.confetti.render();
`

Angular 9 support?

Is it possible to use this library with Angular using typescript?

I tried using it using the following method. Am I doing something wrong?

donate.component.ts

import ConfettiGenerator from "confetti-js";
import { jQuery } from 'jquery';
declare var jQuery: any;
.
@Component({
   ....
})
export class DonateComponent implements OnInit {
  public confetti;
  @ViewChild('confettiBody') confettiBody: ElementRef;

  ngOnInit() {
    // var confettiSettings = { target: 'confettiBody' };    // Method 1
    var confettiSettings = { target: this.confettiBody };       // Method 2
    this.confetti = new ConfettiGenerator(confettiSettings); 
  }
  dropConfetti() {
    console.log('dropping confetti');
    this.confetti.render();
  }
}

donate.component.html

<!-- Successful Donation Modal -->
<div #successfulDonationModal class="modal fade" id="successfulDonationModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div #confettiBody class="modal-body text-center" id="confettiBody">
        <img class="img-fluid" src="assets/img/26.png" alt="smiley-face">
        <h1 class="pt-4">THANK YOU!!</h1>
        <h1 class="">FOR DONATING</h1>
      </div>
    </div>
  </div>
</div>

Have tried direct reference using method 1 and also jquery elemRef via method 2 mentioned in donate.component.ts above, both didn't work. Here is the error stack in both:

ERROR TypeError: Cannot read property 'getContext' of null
    at new ConfettiGenerator (index.es.js:52)
    at DonateComponent.ngOnInit (donate.component.ts:28)
    at callHook (core.js:3937)
    at callHooks (core.js:3901)
    at executeInitAndCheckHooks (core.js:3842)
    at refreshView (core.js:11795)
    at refreshDynamicEmbeddedViews (core.js:13142)
    at refreshView (core.js:11800)
    at refreshComponent (core.js:13217)
    at refreshChildComponents (core.js:11508)
defaultErrorLogger @ core.js:5873 ...........

Is it even possible to do this from the typescript side or have to include .js file to do this for Angular 9?

White screen rendering when given options

Hi there!

If I render this with other options in the main object, it renders a white screen using react.

I also get the below error :

index.min.js:1 Uncaught (in promise) TypeError: Cannot read property 'getContext' of null
at new ./node_modules/confetti-js/dist/index.min.js.window.ConfettiGenerator (index.min.js:1)

Ionic issue

Hi,
This works good in ionic4 but not managed to render prop->svg
Someone to help me?

thx

Performance issues on Firefox

Hey! So everything seems fine on android and iOS but I got serious slow performance on Firefox after 10-15 sec and it's getting worst overtime.

Here is my code ("confetti-js": "0.0.17"):

const confettiSettings = { target: 'confetti-canvas', "max":"15", "size":"1", "start_from_edge":false, "respawn":true, "animate":false, "props":[
				{"type":"svg","src": this.state.storageURL + 'SVG/BC_p_line.svg',"size":25,"weight":0.05},
				{"type":"svg","src": this.state.storageURL + 'SVG/BC_p_circle_green.svg',"size":15,"weight":0.15},
				{"type":"svg","src": this.state.storageURL + 'SVG/BC_p_circle.svg',"size":15,"weight":0.15},
				{"type":"svg","src": this.state.storageURL + 'SVG/BC_p_square.svg',"size":7,"weight":0.15},
				{"type":"svg","src": this.state.storageURL + 'SVG/BC_p_dots.svg',"size":35,"weight":0.15},
				{"type":"svg","src": this.state.storageURL + 'SVG/BC_p_dots_green.svg',"size":35,"weight":0.15}   ], "colors":[[0,255,209]], "clock":"8", "rotate":true};
				const confetti = new ConfettiGenerator(confettiSettings);
				confetti.render();

Is this problem related?
https://gamedev.stackexchange.com/questions/37298/slow-firefox-javascript-canvas-performance

Pause function

Is there any method to pause animation? It should be nice if it exists. For example, in my case, I use confetti-js with custom svg assets and I want to stop animation after a while and use it like a static random background
confetti

.clear() not working

When I try to call .clear() nothing happens and the confetti remains running. I try and call in in a Set Timeout function like this:

const confettiSettings = { target: 'my-canvas' }
const confetti = new ConfettiGenerator(confettiSettings)
const canvas = $('#my-canvas')
const confettiRain = function () {
  confetti.render()
  setTimeout(() => {
    confetti.clear()
  }, 5000)
}

Can you show some examples of how you one would call this?

Allow passing reference by node instead of ID string

The way you're suggesting it work with React is really non-standard; how you'd normally do things is to create a ref, pass that to your canvas element in your JSX, then pass the DOM element ref to whatever library you're running in the side-effect.

This is pretty much almost possible with confetti-js but the target param should also take an actual node instead of just an ID string (requiring an ID string also requires generating a unique ID string for every usage on page). I may write a PR tomorrow to this end.

Confetti doesn't fit to expanding window

When a window is initially not in full screen on initial load and is then expanded, the confetti is cut off and only loads for the initial size of the window. This works correctly when the window is fullscreen on the initial load and is minimized than re-expanded.

This was tested using react in the chrome browser.

Here is an example:
image

Issues displaying svg prop that's not located in the same folder

Hello @Agezao Thank you for this wonderful plugin.

I've been trying to use the new svg prop functionality to include a new image but every-time that I added a svg attribute to the settings payload I'm getting the following error:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

Seems like a problem with the drawImage function like if the image is invalid, I've tried different formats including, png, jpg and svg but all of them triggered the same issue

https://github.com/Agezao/confetti-js/blob/master/src/confetti.js#L137

Usage:
Screen Shot 2019-11-13 at 12 49 56 PM

Any idea?

Canvas alignment altered before / after confetti annimation.

I have css aligning my canvas to the center of the screen. When I run render() I see the animation as expected and when I run clear it resets my canvas. However, when it resets my canvas to the left when it is meant to be in the center.

I think these lines are generally unrelated, but when looking at the source code they jumped out to me and dont look to be correct:

confetti-js/src/confetti.js

Lines 184 to 186 in 27cc175

var w = cv.width;
cv.width = 1;
cv.width = w;

Spawn positions

A couple minor things I noticed with spawn positions:

  • If the size is big enough, parts of the confetti are still on screen when they appear and disappear
  • if the clock is set to a negative number they animate backwards but don't restart when they reach the top

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.