Full Code of catdad/canvas-confetti for AI

master 20eebad51dde cached
26 files
121.5 KB
34.6k tokens
36 symbols
1 requests
Download .txt
Repository: catdad/canvas-confetti
Branch: master
Commit: 20eebad51dde
Files: 26
Total size: 121.5 KB

Directory structure:
gitextract_25sgzoeb/

├── .brackets.json
├── .editorconfig
├── .eslintrc.yml
├── .gitattributes
├── .github/
│   ├── funding.yml
│   └── workflows/
│       └── ci.yml
├── .gitignore
├── .npmignore
├── .npmrc
├── LICENSE
├── README.md
├── bin/
│   └── on_failure.sh
├── build/
│   ├── .eslintrc.yml
│   ├── build.js
│   └── serve.js
├── fixtures/
│   ├── debug.html
│   ├── page.browserify.html
│   ├── page.html
│   ├── page.minified.html
│   └── page.module.html
├── index.html
├── package.json
├── src/
│   └── confetti.js
└── test/
    ├── .eslintrc.yml
    ├── index.test.js
    └── ssr.test.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .brackets.json
================================================
{
    "spaceUnits": 2,
    "useTabChar": false,
    "language": {
        "javascript": {
            "linting.prefer": [
                "ESLint"
            ],
            "linting.usePreferredOnly": true
        },
        "markdown": {
            "wordWrap": true
        }
    },
    "language.fileNames": {
        "Jenkinsfile": "groovy"
    },
    "language.fileExtensions": {
      "mjs": "javascript"
    }
}


================================================
FILE: .editorconfig
================================================
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[{package.json,*.yml}]
indent_size = 2


================================================
FILE: .eslintrc.yml
================================================
extends:
  - eslint:recommended
env:
  es6: false
  browser: true
  node: true
rules:
  semi: [ error, always ]


================================================
FILE: .gitattributes
================================================
# Auto detect text files and perform LF normalization
* text=auto

*.js     text eol=lf
*.jsx    text eol=lf
*.json   text eol=lf
*.html   text eol=lf
*.md     text eol=lf
*.yml    text eol=lf
*.css    text eol=lf
*.less   text eol=lf
*.scss   text eol=lf
*.sass   text eol=lf
*.svg    text eol=lf
*.xml    text eol=lf
*.sh     text eol=lf

# Custom for Visual Studio
*.cs     diff=csharp

# Standard to msysgit
*.doc    diff=astextplain
*.DOC    diff=astextplain
*.docx   diff=astextplain
*.DOCX   diff=astextplain
*.dot    diff=astextplain
*.DOT    diff=astextplain
*.pdf    diff=astextplain
*.PDF    diff=astextplain
*.rtf    diff=astextplain
*.RTF    diff=astextplain


================================================
FILE: .github/funding.yml
================================================
github: catdad
custom: ["https://www.paypal.me/kirilvatev", "https://venmo.com/Kiril-Vatev"]


================================================
FILE: .github/workflows/ci.yml
================================================
name: CI

on:
  push:
  pull_request:
    branches: [master]

permissions:
  id-token: write
  contents: read

env:
  FORCE_COLOR: 1

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-node@v6
        with:
          node-version: 24
          registry-url: https://registry.npmjs.org/
      - run: npm install
      - run: npm run lint
      - run: npm test
      - run: npm pack --dry-run
      - run: npm publish
        if: startsWith(github.ref, 'refs/tags/') && github.event_name != 'pull_request'
      - uses: actions/upload-artifact@v4
        if: ${{ failure() }}
        with:
          name: test-screenshots
          path: shots/


================================================
FILE: .gitignore
================================================
# Windows image file caches
Thumbs.db
ehthumbs.db
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows shortcuts
*.lnk

# OSX
.DS_Store
.AppleDouble
.LSOverride

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

# Node stuff
node_modules/
coverage/
.nyc_output/

# project-specific stuff
shots/
dist/
temp/


================================================
FILE: .npmignore
================================================
# Windows image file caches
Thumbs.db
ehthumbs.db
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows shortcuts
*.lnk

# OSX
.DS_Store
.AppleDouble
.LSOverride

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

# Node stuff
node_modules/
coverage/
.nyc_output/

# project-specific stuff
bin/
test/
shots/
temp/
build/
fixtures/
index.html

# dotfiles don't need to be in npm
.*


================================================
FILE: .npmrc
================================================
package-lock=false


================================================
FILE: LICENSE
================================================
ISC License

Copyright (c) 2020, Kiril Vatev

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


================================================
FILE: README.md
================================================
# [![Canvas Confetti](https://cdn.jsdelivr.net/gh/catdad-experiments/catdad-experiments-org@5ed78b/canvas-confetti/logo.jpg)](https://github.com/catdad/canvas-confetti/)

[![github actions ci][ci.svg]][ci.link]
[![jsdelivr][jsdelivr.svg]][jsdelivr.link]
[![npm-downloads][npm-downloads.svg]][npm.link]
[![npm-version][npm-version.svg]][npm.link]

[ci.svg]: https://github.com/catdad/canvas-confetti/actions/workflows/ci.yml/badge.svg
[ci.link]: https://github.com/catdad/canvas-confetti/actions/workflows/ci.yml?query=branch%3Amaster
[jsdelivr.svg]: https://data.jsdelivr.com/v1/package/npm/canvas-confetti/badge?style=rounded
[jsdelivr.link]: https://www.jsdelivr.com/package/npm/canvas-confetti
[npm-downloads.svg]: https://img.shields.io/npm/dm/canvas-confetti.svg
[npm.link]: https://www.npmjs.com/package/canvas-confetti
[npm-version.svg]: https://img.shields.io/npm/v/canvas-confetti.svg

## Demo

[catdad.github.io/canvas-confetti](https://catdad.github.io/canvas-confetti/)

## Install

You can install this module as a component from NPM:

```bash
npm install --save canvas-confetti
```

You can then `require('canvas-confetti');` to use it in your project build. _Note: this is a client component, and will not run in Node. You will need to build your project with something like [webpack](https://github.com/webpack/webpack) in order to use this._

You can also include this library in your HTML page directly from a CDN:

```html
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.4/dist/confetti.browser.min.js"></script>
```

_Note: you should use the latest version at the time that you include your project. You can see all versions [on the releases page](https://github.com/catdad/canvas-confetti/releases)._

## Reduced Motion

Thank you for joining me in this very important message about motion on your website. See, [not everyone likes it, and some actually prefer no motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion). They have [ways to tell us about it](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion) and we should listen. While I don't want to go as far as tell you not to have confetti on your page just yet, I do want to make it easy for you to respect what your users want. There is a `disableForReducedMotion` option you can use so that users that have trouble with chaotic animations don't need to struggle on your website. This is disabled by default, but I am considering changing that in a future major release. If you have strong feelings about this, [please let me know](https://github.com/catdad/canvas-confetti/issues/new). For now, please confetti responsibly.

## API

When installed from `npm`, this library can be required as a client component in your project build. When using the CDN version, it is exposed as a `confetti` function on `window`.

### `confetti([options {Object}])` → `Promise|null`

`confetti` takes a single optional object. When `window.Promise` is available, it will return a Promise to let you know when it is done. When promises are not available (like in IE), it will return `null`. You can polyfill promises using any of the popular polyfills. You can also provide a promise implementation to `confetti` through:

```javascript
const MyPromise = require('some-promise-lib');
const confetti = require('canvas-confetti');
confetti.Promise = MyPromise;
```

If you call `confetti` multiple times before it is done, it will return the same promise every time. Internally, the same canvas element will be reused, continuing the existing animation with the new confetti added. The promise returned by each call to `confetti` will resolve once all animations are done.

#### `options`

The `confetti` parameter is a single optional `options` object, which has the following properties:

- `particleCount` _Integer (default: 50)_: The number of confetti to launch. More is always fun... but be cool, there's a lot of math involved.
- `angle` _Number (default: 90)_: The angle in which to launch the confetti, in degrees. 90 is straight up.
- `spread` _Number (default: 45)_: How far off center the confetti can go, in degrees. 45 means the confetti will launch at the defined `angle` plus or minus 22.5 degrees.
- `startVelocity` _Number (default: 45)_: How fast the confetti will start going, in pixels.
- `decay` _Number (default: 0.9)_: How quickly the confetti will lose speed. Keep this number between 0 and 1, otherwise the confetti will gain speed. Better yet, just never change it.
- `gravity` _Number (default: 1)_: How quickly the particles are pulled down. 1 is full gravity, 0.5 is half gravity, etc., but there are no limits. You can even make particles go up if you'd like.
- `drift` _Number (default: 0)_: How much to the side the confetti will drift. The default is 0, meaning that they will fall straight down. Use a negative number for left and positive number for right.
- `flat` _Boolean (default: false)_: Optionally turns off the tilt and wobble that three dimensional confetti would have in the real world. Yeah, they look a little sad, but y'all asked for them, so don't blame me.
- `ticks` _Number (default: 200)_: How many times the confetti will move. This is abstract... but play with it if the confetti disappear too quickly for you.
- `origin` _Object_: Where to start firing confetti from. Feel free to launch off-screen if you'd like.
  - `origin.x` _Number (default: 0.5)_: The `x` position on the page, with `0` being the left edge and `1` being the right edge.
  - `origin.y` _Number (default: 0.5)_: The `y` position on the page, with `0` being the top edge and `1` being the bottom edge.
- `colors` _Array&lt;String&gt;_: An array of color strings, in the HEX format... you know, like `#bada55`.
- `shapes` _Array&lt;String|Shape&gt;_: An array of shapes for the confetti. There are 3 built-in values of `square`, `circle`, and `star`. The default is to use both squares and circles in an even mix. To use a single shape, you can provide just one shape in the array, such as `['star']`. You can also change the mix by providing a value such as `['circle', 'circle', 'square']` to use two third circles and one third squares. You can also create your own shapes using the [`confetti.shapeFromPath`](#confettishapefrompath-path-matrix---shape) or [`confetti.shapeFromText`](#confettishapefromtext-text-scalar-color-fontfamily---shape) helper methods.
- `scalar` _Number (default: 1)_: Scale factor for each confetti particle. Use decimals to make the confetti smaller. Go on, try teeny tiny confetti, they are adorable!
- `zIndex` _Integer (default: 100)_: The confetti should be on top, after all. But if you have a crazy high page, you can set it even higher.
- `disableForReducedMotion` _Boolean (default: false)_: Disables confetti entirely for users that [prefer reduced motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion). The `confetti()` promise will resolve immediately in this case.

### `confetti.shapeFromPath({ path, matrix? })` → `Shape`

This helper method lets you create a custom confetti shape using an [SVG Path string](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d). Any valid path should work, though there are a few caveats:
- All paths will be filed. If you were hoping to have a stroke path, that is not implemented.
- Paths are limited to a single color, so keep that in mind.
- All paths need a valid transform matrix. You can pass one in, or you can leave it out and use this helper to calculate the matrix for you. Do note that calculating the matrix is a bit expensive, so it is best to calculate it once for each path in development and cache that value, so that production confetti remain fast. The matrix is deterministic and will always be the same given the same path value.
- For best forward compatibility, it is best to re-generate and re-cache the matrix if you update the `canvas-confetti` library.
- Support for path-based confetti is limited to browsers which support [`Path2D`](https://developer.mozilla.org/en-US/docs/Web/API/Path2D), which should really be all major browser at this point.

This method will return a `Shape` -- it's really just a plain object with some properties, but shhh... we'll pretend it's a shape. Pass this `Shape` object into the `shapes` array directly.

As an example, here's how you might do a triangle confetti:

```javascript
var triangle = confetti.shapeFromPath({ path: 'M0 10 L5 0 L10 10z' });

confetti({
  shapes: [triangle]
});
```

### `confetti.shapeFromText({ text, scalar?, color?, fontFamily? })` → `Shape`

This is the highly anticipated feature to render emoji confetti! Use any standard unicode emoji. Or other text, but... maybe don't use other text.

While any text should work, there are some caveats:
- For flailing confetti, something that is mostly square works best. That is, a single character, especially an emoji.
- Rather than rendering text every time a confetti is drawn, this helper actually rasterizes the text. Therefore, it does not scale well after it is created. If you plan to use the `scalar` value to scale your confetti, use the same `scalar` value here when creating the shape. This will make sure the confetti are not blurry.

The options for this method are:
- `options` _`Object`_:
  - `text` _`String`_: the text to be rendered as a confetti. If you can't make up your mind, I suggest "🐈".
  - `scalar` _`Number, optional, default: 1`_: a scale value relative to the default size. It matches the `scalar` value in the confetti options.
  - `color` _`String, optional, default: #000000`_: the color used to render the text.
  - `fontFamily` _`String, optional, default: native emoji`_: the font family name to use when rendering the text. The default follows [best practices for rendring the native OS emoji of the device](https://nolanlawson.com/2022/04/08/the-struggle-of-using-native-emoji-on-the-web/), falling back to `sans-serif`. If using a web font, make sure this [font is loaded](https://developer.mozilla.org/en-US/docs/Web/API/FontFace/load) before rendering your confetti.

```javascript
var scalar = 2;
var pineapple = confetti.shapeFromText({ text: '🍍', scalar });

confetti({
  shapes: [pineapple],
  scalar
});
```

### `confetti.create(canvas, [globalOptions])` → `function`

This method creates an instance of the `confetti` function that uses a custom canvas. This is useful if you want to limit the area on your page in which confetti appear. By default, this method will not modify the canvas in any way (other than drawing to it).

_Canvas can be misunderstood a bit though, so let me explain why you might want to let the module modify the canvas just a bit. By default, a `canvas` is a relatively small image -- somewhere around 300x150, depending on the browser. When you resize it using CSS, this sets the display size of the canvas, but not the image being represented on that canvas. Think of it as loading a 300x150 jpeg image in an `img` tag and then setting the CSS for that tag to `1500x600` -- your image will end up stretched and blurry. In the case of a canvas, you need to also set the width and height of the canvas image itself. If you don't want to do that, you can allow `confetti` to set it for you._

Note also that you should persist the custom instance and avoid initializing an instance of confetti with the same canvas element more than once.

The following global options are available:
* `resize` _Boolean (default: false)_: Whether to allow setting the canvas image size, as well as keep it correctly sized if the window changes size (e.g. resizing the window, rotating a mobile device, etc.). By default, the canvas size will not be modified.
* `useWorker` _Boolean (default: false)_: Whether to use an asynchronous web worker to render the confetti animation, whenever possible. This is turned off by default, meaning that the animation will always execute on the main thread. If turned on and the browser supports it, the animation will execute off of the main thread so that it is not blocking any other work your page needs to do. Using this option will also modify the canvas, but more on that directly below -- do read it. If it is not supported by the browser, this value will be ignored.
* `disableForReducedMotion` _Boolean (default: false)_: Disables confetti entirely for users that [prefer reduced motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion). When set to true, use of this confetti instance will always respect a user's request for reduced motion and disable confetti for them.

_**Important: If you use `useWorker: true`, I own your canvas now. It's mine now and I can do whatever I want with it (don't worry... I'll just put confetti inside it, I promise). You must not try to use the canvas in any way (other than I guess removing it from the DOM), as it will throw an error. When using workers for rendering, control of the canvas must be transferred to the web worker, preventing any usage of that canvas on the main thread. If you must manipulate the canvas in any way, do not use this option.**_

```javascript
var myCanvas = document.createElement('canvas');
document.body.appendChild(myCanvas);

var myConfetti = confetti.create(myCanvas, {
  resize: true,
  useWorker: true
});
myConfetti({
  particleCount: 100,
  spread: 160
  // any other options from the global
  // confetti function
});
```

### `confetti.reset()`

Stops the animation and clears all confetti, as well as immediately resolves any outstanding promises. In the case of a separate confetti instance created with [`confetti.create`](#confetticreatecanvas-globaloptions--function), that instance will have its own `reset` method.

```javascript
confetti();

setTimeout(() => {
  confetti.reset();
}, 100);
```

```javascript
var myCanvas = document.createElement('canvas');
document.body.appendChild(myCanvas);

var myConfetti = confetti.create(myCanvas, { resize: true });

myConfetti();

setTimeout(() => {
  myConfetti.reset();
}, 100);
```

## Examples

Launch some confetti the default way:

```javascript
confetti();
```

Launch a bunch of confetti:

```javascript
confetti({
  particleCount: 150
});
```

Launch some confetti really wide:

```javascript
confetti({
  spread: 180
});
```

Get creative. Launch a small poof of confetti from a random part of the page:

```javascript
confetti({
  particleCount: 100,
  startVelocity: 30,
  spread: 360,
  origin: {
    x: Math.random(),
    // since they fall down, start a bit higher than random
    y: Math.random() - 0.2
  }
});
```

I said creative... we can do better. Since it doesn't matter how many times we call `confetti` (just the total number of confetti in the air), we can do some fun things, like continuously launch more and more confetti for 30 seconds, from multiple directions:

```javascript
// do this for 30 seconds
var duration = 30 * 1000;
var end = Date.now() + duration;

(function frame() {
  // launch a few confetti from the left edge
  confetti({
    particleCount: 7,
    angle: 60,
    spread: 55,
    origin: { x: 0 }
  });
  // and launch a few from the right edge
  confetti({
    particleCount: 7,
    angle: 120,
    spread: 55,
    origin: { x: 1 }
  });

  // keep going until we are out of time
  if (Date.now() < end) {
    requestAnimationFrame(frame);
  }
}());
```


================================================
FILE: bin/on_failure.sh
================================================
green=`tput setaf 2`
reset=`tput sgr0`

line_break () {
  echo --------------------------------------
}

print_green () {
  echo "${green}$@${reset}"
}

upload_file () {
  filename=$1
  urlname=${filename// /_}

  downloadurl=`curl -sS --upload-file "./$filename" https://transfer.sh/$urlname`

  echo image \"$filename\"
  print_green "  uploaded to: $downloadurl"
}

find_files () {
  cd shots

  echo list of files present:
  ls -l
  line_break

  for i in *.png;do upload_file "$i";done
}

find_files


================================================
FILE: build/.eslintrc.yml
================================================
env:
  es6: true
  node: true
  browser: false
parser: babel-eslint
rules:
  no-console: off


================================================
FILE: build/build.js
================================================
const fs = require('fs');
const { promisify } = require('util');

const { name, version, main } = require('../package.json');

const buildDate = (new Date()).toISOString();

function mkdir(dir) {
  return promisify(fs.mkdir)(dir).then(() => {
    return Promise.resolve();
  }).catch(err => {
    if (err.code === 'EEXIST') {
      return Promise.resolve();
    }

    return Promise.reject(err);
  });
}

function readFile(file, encoding) {
  return promisify(fs.readFile)(file, encoding);
}

function writeFile(file, content) {
  return promisify(fs.writeFile)(file, content);
}

function buildCommonJs(content) {
  return `// ${name} v${version} built on ${buildDate}
!(function (window, module) {
// source content
${content}
// end source content

  window.confetti = module.exports;
}(window, {}));
`;
}

function buildModule(content) {
  return `// ${name} v${version} built on ${buildDate}
var module = {};

// source content
${content}
// end source content

export default module.exports;
export var create = module.exports.create;
`;
}

mkdir('dist')
.then(() => readFile(main))
.then(file => {
  return Promise.all([
    writeFile('dist/confetti.browser.js', buildCommonJs(file)),
    writeFile('dist/confetti.module.mjs', buildModule(file))
  ]);
})
.catch(err => {
  console.error(err);
  process.exitCode = 1;
});


================================================
FILE: build/serve.js
================================================
const path = require('path');
const http = require('http');
const send = require('send');
const root = require('rootrequire');
const { networkInterfaces } = require('os');

const PORT = 9001;

http.createServer(function (req, res) {
  const url = req.url === '/' ? '/index.html' : req.url;
  const file = path.resolve(root, url.slice(1));

  console.log(req.method, url, '->', file);

  const cspRules = [
    `default-src 'self' https://cdnjs.cloudflare.com`,
    `img-src * data: blob:`,
    `media-src * data: blob:`,
    `font-src https://fonts.googleapis.com https://fonts.gstatic.com`,
    `style-src 'self' 'unsafe-inline' https://fonts.googleapis.com`,
    `script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com`,
    `worker-src 'self' blob:`
  ];

  res.setHeader('content-security-policy', cspRules.join('; '));

  send(req, file).pipe(res);
}).listen(PORT, () => {
  console.log('listening at:');
  console.log(`  http://localhost:${PORT}`);

  Object.values(networkInterfaces())
    .reduce((memo, value) => [...memo, ...value], [])
    .filter(value => value.family === 'IPv4')
    .forEach(({ address }) => console.log(`  http://${address}:${PORT}`));
});


// twitch csp... see !112
//  default-src 'self' https://6rh8h42nhnjmirlyxc0w9lbpmeehi0.ext-twitch.tv
//  block-all-mixed-content
//  img-src * data: blob:
//  media-src * data: blob:
//  frame-ancestors https://supervisor.ext-twitch.tv https://extension-files.twitch.tv https://*.twitch.tv https://*.twitch.tech https://localhost.twitch.tv:* https://localhost.twitch.tech:* http://localhost.rig.twitch.tv:*
//  font-src https://6rh8h42nhnjmirlyxc0w9lbpmeehi0.ext-twitch.tv https://fonts.googleapis.com https://fonts.gstatic.com
//  style-src 'self' 'unsafe-inline' https://6rh8h42nhnjmirlyxc0w9lbpmeehi0.ext-twitch.tv https://fonts.googleapis.com
//  connect-src https: wss: https://www.google-analytics.com https://stats.g.doubleclick.net
//  script-src 'self' https://6rh8h42nhnjmirlyxc0w9lbpmeehi0.ext-twitch.tv https://extension-files.twitch.tv https://www.google-analytics.com


================================================
FILE: fixtures/debug.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Debug emoji confetti</title>
</head>
<body>
  <script>
    // this page is a demo that is not built, so fudge the module.exports support
    // define a global `module` so that the actual source file can use it
    window.module = {};
  </script>
  <script src="../src/confetti.js"></script>
  <script>
    // define the `module.exports` as the `confetti` global, the way that the
    // cdn distributed file would
    window.confetti = module.exports;
  </script>

  <p><button id="test-confetti">Emoji confetti test</button></p>
  <canvas id="debug-canvas" width="600" height="650" style="outline: 1px solid red"></canvas>
  <p id="test-text"></p>

  <script>
    const loadFonts = async () => {
      const isSafari = navigator.vendor === 'Apple Computer, Inc.';
      const fontName = 'Noto Color Emoji';

      await Promise.all([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(n => {
        const safari = `url(https://fonts.gstatic.com/s/notocoloremoji/v25/Yq6P-KqIXTD0t4D9z1ESnKM3-HpFabts6diysYTngZPnMC1MfLd4hQ.${n}.woff2)`;
        const realBrowser = `url(https://fonts.gstatic.com/s/notocoloremoji/v25/Yq6P-KqIXTD0t4D9z1ESnKM3-HpFabsE4tq3luCC7p-aXxcn.${n}.woff2)`;

        const fontFile = new FontFace(
          fontName,
          isSafari ? safari : realBrowser
        );

        document.fonts.add(fontFile);

        return fontFile.load();
      }));

      return `"${fontName}"`;
    };

    const connectTest = ({ fontFamily }) => {
      const button = document.getElementById('test-confetti');

      const scalar = 3;

      // make this a getter so that the shapes don't initialize on page load
      const getShapes = ((shapes) => () => {
        if (shapes.length) {
          return shapes;
        }

        shapes = [
          ['🦄', '🍑', '🤣', '🐈', 'bg'].map(text => confetti.shapeFromText({ text, scalar })),
          ['🦄', '🍑', '🤣', '🐈', 'bg'].map(text => confetti.shapeFromText({ text, scalar, fontFamily }))
        ];

        return shapes;
      })([]);

      button.onclick = () => {
        const [shapesDefault, shapesFont] = getShapes();

        confetti({
          particleCount: 10,
          shapes: shapesDefault,
          scalar,
          origin: { y: 0.7, x: 0.25 }
        });
        confetti({
          particleCount: 10,
          shapes: shapesFont,
          scalar,
          origin: { y: 0.7, x: 0.75 }
        });
      };
    };

    const drawBitmapToCanvas = (bitmap) => {
      const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
      const ctx = canvas.getContext('2d');

      ctx.drawImage(bitmap, 0, 0);

      return canvas;
    };

    const drawTransformedEmoji = async ({ fontFamily, canvas, ctx, offsetX = 0, offsetY = 0 }) => {
      ['🦄', '🍑', '🤣', '🐈'].forEach((text, idx) => {
        const shape1 = confetti.shapeFromText({ text, scalar: 1, fontFamily });
        const shape2 = confetti.shapeFromText({ text, scalar: 2, fontFamily });
        const shape5 = confetti.shapeFromText({ text, scalar: 5, fontFamily });

        const y = idx * 100 + 50 + offsetY;

        ctx.drawImage(shape1.bitmap, 0, y);
        ctx.drawImage(shape2.bitmap, 100, y);
        ctx.drawImage(shape5.bitmap, 200, y);

        [[shape1, 1], [shape2, 2], [shape5, 5]].forEach(([shape, scale], j) => {
          const x = 300 + (j * 100) + offsetX;

          const rotation = 3.2;
          const scaleX = scale * 0.8;
          const scaleY = scale * 1.4;

          var matrix = new DOMMatrix([
            Math.cos(rotation) * scaleX,
            Math.sin(rotation) * scaleX,
            -Math.sin(rotation) * scaleY,
            Math.cos(rotation) * scaleY,
            x,
            y
          ]);
          matrix.multiplySelf(new DOMMatrix(shape.matrix));

          const pattern = (() => {
            try {
              // most browsers support this, it's spec
              return ctx.createPattern(shape.bitmap, 'no-repeat');
            } catch (e) {
              // safari doesn't, because of course it doesn't
              // so draw the bitmap to a canvas first and create a
              // pattern from that canvas
              console.log('failed to create bitmap pattern:', e);
              return ctx.createPattern(drawBitmapToCanvas(shape.bitmap), 'no-repeat');
            }
          })();

          pattern.setTransform(matrix);

          ctx.fillStyle = pattern;
          ctx.fillRect(x - 100, y - 100, 300, 300);
        });
      });
    };

    const drawDebugEmoji = async ({ fontFamily, canvas, ctx, offsetX = 0, offsetY = 0 }) => {
      const text = '🦄';

      const draw = ({ offsetX, offsetY, fontFamily }) => {
        const opts = { text, scalar: 15 };

        if (fontFamily) {
          opts.fontFamily = fontFamily;
        }

        const shape = confetti.shapeFromText(opts);

        ctx.drawImage(shape.bitmap, offsetX, offsetY);

        ctx.lineWidth = 1;
        ctx.strokeStyle = 'orange';
        ctx.strokeRect(offsetX, offsetY, shape.bitmap.width, shape.bitmap.height);

        return { width: shape.bitmap.width, height: shape.bitmap.height };
      };

      const { width, height: height1 } = draw({ offsetX: 10 + offsetX, offsetY: 10 + offsetY });
      const { height: height2 } = draw({ offsetX: 20 + width + offsetX, offsetY: 10 + offsetY, fontFamily });

      return Math.max(height1, height2);
    };

    const renderTestText = ({ fontFamily }) => {
      const fontSize = '20px';
      const text = document.getElementById('test-text');

      const withFont = document.createElement('div');
      Object.assign(withFont.style, { fontFamily, fontSize });
      withFont.appendChild(document.createTextNode(`plain text in ${fontFamily}: 🦄 🍑 🤣`));

      const withSystemUI = document.createElement('div');
      Object.assign(withSystemUI.style, { fontFamily: '"system ui"', fontSize });
      withSystemUI.appendChild(document.createTextNode(`plain text in "system ui": 🦄 🍑 🤣`));

      text.appendChild(withFont);
      text.appendChild(withSystemUI);
    };

    Promise.resolve().then(async () => {
      // const fontFamily = null;
      const fontFamily = await loadFonts();

      const canvas = document.querySelector('#debug-canvas');
      const ctx = canvas.getContext('2d');

      renderTestText({ fontFamily });

      connectTest({ fontFamily, canvas, ctx });

      await drawDebugEmoji({ fontFamily, canvas, ctx });
      await drawTransformedEmoji({ fontFamily, canvas, ctx, offsetY: 200 });
    }).catch(e => {
      console.log('something went wrong:', e);
    });
  </script>
</body>
</html>


================================================
FILE: fixtures/page.browserify.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test harness</title>
</head>
<body>
  <script src="/temp/confetti.bundle.js"></script>

  <script>
    document.addEventListener('click', function () {
      confetti();
    });
  </script>
</body>
</html>


================================================
FILE: fixtures/page.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test harness</title>

  <style>
    html, body {
      padding: 0;
      margin: 0;
      width: 100%;
      height: 100%;
    }
  </style>
</head>
<body>
  <script src="/dist/confetti.browser.js"></script>
</body>
</html>


================================================
FILE: fixtures/page.minified.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test harness</title>
</head>
<body>
  <script src="/temp/confetti.min.js"></script>

  <script>
    document.addEventListener('click', function () {
      confetti();
    });
  </script>
</body>
</html>


================================================
FILE: fixtures/page.module.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test harness</title>

  <style>
    html, body {
      padding: 0;
      margin: 0;
      width: 100%;
      height: 100%;
    }
  </style>
</head>
<body>
  <script type="module">
    import confetti, { create } from '/dist/confetti.module.mjs';

    if (window.confetti) {
      throw 'nope';
    }

    window.confettiAlias = confetti;
    window.createAlias = create;
  </script>
</body>
</html>


================================================
FILE: index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Component for drawing confetti on a canvas">
  <meta name="author" content="Kiril Vatev">
  <meta name="keywords" content="canvas,confetti,component,module,animation,javascript,catdad">

  <meta name="theme-color" content="#393939">
  <link id="favicon" rel="shortcut icon" type="image/png" />

  <title>canvas confetti</title>

  <link href="https://fonts.googleapis.com/css2?family=Noto+Sans&display=swap" rel="stylesheet">

  <style>
    :root {
      --primary-color: #eeeeee;
      --secondary-color: #363636;
      --secondary-variant-color: #272727;
      --background-color: #212121;
      --inner-color: #ffffff;
      --border-color: #555651;

      /* icons by Google - Material Design
       * https://material.io/resources/icons/?style=baseline
       */
      --switch-moon-white: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' %3E%3Cpath fill='%23eeeeee' d='M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6z'%3E%3C/path%3E%3C/svg%3E");
      --switch-sun-black: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' %3E%3Cpath fill='%23212121' d='M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z'%3E%3C/path%3E%3C/svg%3E");
      --switch-auto-white: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' %3E%3Cpath fill='%23eeeeee' d='M10.85 12.65h2.3L12 9l-1.15 3.65zM20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM14.3 16l-.7-2h-3.2l-.7 2H7.8L11 7h2l3.2 9h-1.9z'%3E%3C/path%3E%3C/svg%3E");
      --switch-auto-black: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' %3E%3Cpath fill='%23212121' d='M10.85 12.65h2.3L12 9l-1.15 3.65zM20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM14.3 16l-.7-2h-3.2l-.7 2H7.8L11 7h2l3.2 9h-1.9z'%3E%3C/path%3E%3C/svg%3E");

      --theme-switch: var(--switch-moon-white);
    }

    [data-theme="light"] {
      --primary-color: #212121;
      --secondary-color: #ffffff;
      --background-color: #f0f0f0;
      --inner-color: #363636;

      --theme-switch: var(--switch-sun-black);
    }

    [auto-theme] {
      --theme-switch: var(--switch-auto-white);
    }

    [data-theme="light"][auto-theme] {
      --theme-switch: var(--switch-auto-black);
    }
    
    html {
      scroll-behavior: smooth;
    }

    html, body {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
    }

    body {
      background: var(--background-color);
      color: var(--primary-color);
      font-size: 1em;
      font-family: 'Noto Sans', sans-serif;
    }

    * {
      box-sizing: border-box;
    }

    .sprite {
      display: none;
    }

    header {
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 100%;
      height: 64px;
    }

    .theme {
      --size: 28px;
      position: relative;
      display: inline-block;
      width: var(--size);
      height: var(--size);
      background: none;
      border: none;
      outline: none;
      margin-right: 12px;
      cursor: pointer;
    }

    .theme:after {
      position: absolute;
      top: 0;
      left: 0;
      content: "";
      width: var(--size);
      height: var(--size);
      background-repeat: no-repeat;
      background-position: center;
      background: var(--theme-switch);
    }

    .github-icon {
      --size: 36px;
      position: relative;
      display: block;
      width: var(--size);
      height: var(--size);
      margin-right: 12px;
    }

    .github-icon svg.icon {
      fill: var(--primary-color);
    }

    h1, h2, .center {
      text-align: center;
    }

    h1 {
      margin-top: 64px;
    }

    h2 {
      padding: 0;
      margin: 0.25em;
    }

    p {
      margin: 0.5em;
    }

    .container {
      position: relative;
      max-width: 1000px;
      width: 100%;
      margin: 0 auto;
    }

    .group {
      position: relative;
      width: 100%;
      margin: 40px 0;
      padding-top: 16px;

      border-top: 1px solid var(--border-color);
      border-radius: 20px;
    }

    .run {
      padding: 10px 6px;
      margin: 0.75em auto;
      max-width: 200px;
      width: 100%;
      display: inline-block;

      background: var(--secondary-color);
      border: none;
      outline: none;

      color: var(--inner-color);
      font-weight: bold;
      cursor: pointer;
      user-select: none;

      opacity: 0.8;
      transition: opacity 100ms ease;
    }

    .group .run:hover {
      opacity: 1;
    }

    .editor {
      position: relative;
      min-height: 100px;
      width: 100%;
    }

    .editor.ace_dark.ace_editor {
      background-color: var(--secondary-color);
    }
    .editor.ace_dark .ace_gutter {
      background: var(--secondary-variant-color);
    }
    .editor.ace_dark .ace_gutter .ace_gutter-cell {
      color: var(--inner-color);
      opacity: 0.6;
    }

    .flex-rows {
      position: relative;
      display: block;
      width: 100%;
      padding-bottom: 1em;
    }

    .description {
      width: 94%;
      margin: 10px auto;
      padding: 0;

      align-items: center;
      line-height: 1.5;
    }

    .left {
      flex-grow: 1;
      display: flex;
      flex-direction: column;
    }

    a.anchor {
      position: relative;
      color: currentColor;
      text-decoration: none;
    }

    a.anchor:hover::before {
      content: "🔗";
      color: currentColor;
      position: absolute;
      left: -2rem;
      top: 0;
      transform: scale(0.75, 0.75);
    }

    footer {
      font-size: 0.9rem;
      text-align: center;
      line-height: 2;

      background: var(--secondary-color);
    }

    footer span {
      vertical-align: middle;
    }

    span.icon {
      position: relative;
      display: inline-block;
      height: 1em;
      width: 1em;
    }
    svg.icon {
      position: absolute;
      pointer-events: none;
      left: 0;
      width: 100%;
      height: 100%;

      fill: var(--inner-color);
    }

    footer a {
      text-decoration: none;
      color: var(--inner-color);
      opacity: 0.85;
      will-change: opacity;
    }

    footer a:hover {
      opacity: 1;
    }

    .custom-canvas {
      margin-top: 30px;
      width: 100%;
      max-width: 1000px;
      height: 380px;
      background: var(--secondary-color);
    }

    @media (min-width: 44em) {
      .container {
        width: 95%;
      }

      .flex-rows {
        display: flex;
        flex-direction: row;
      }

      .description {
        width: 66%;
        padding: 0 0 0 1em;
      }
    }
  </style>

  <script>
    // this page is a demo that is not built, so fudge the module.exports support
    // define a global `module` so that the actual source file can use it
    window.module = {};
  </script>
  <script src="src/confetti.js"></script>
  <script>
    // define the `module.exports` as the `confetti` global, the way that the
    // cdn distributed file would
    window.confetti = module.exports;
  </script>

  <script defer src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.3.0/ace.js"></script>
  <script defer src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify.min.js"></script>
</head>
<body>

  <svg class="sprite" xmlns="http://www.w3.org/2000/svg">
    <defs>
      <symbol id="code" viewBox="0 0 14 16">
        <!-- Icon from GitHub Octicons - https://github.com/primer/octicons/ -->
        <path d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3 9.5 3ZM4.5 3L0 8 4.5 13 6 11.5 2.5 8 6 4.5 4.5 3 4.5 3Z"/>
      </symbol>

      <symbol id="heart" viewBox="0 0 12 16">
        <!-- Icon from GitHub Octicons - https://github.com/primer/octicons/ -->
        <path d="M11.2 3C10.68 2.37 9.95 2.05 9 2 8.03 2 7.31 2.42 6.8 3 6.29 3.58 6.02 3.92 6 4 5.98 3.92 5.72 3.58 5.2 3 4.68 2.42 4.03 2 3 2 2.05 2.05 1.31 2.38 0.8 3 0.28 3.61 0.02 4.28 0 5 0 5.52 0.09 6.52 0.67 7.67 1.25 8.82 3.01 10.61 6 13 8.98 10.61 10.77 8.83 11.34 7.67 11.91 6.51 12 5.5 12 5 11.98 4.28 11.72 3.61 11.2 2.98L11.2 3Z"/>
      </symbol>

      <symbol id="run" viewBox="0 0 10 10">
        <path d="M2 2L8 6L2 10" />
      </symbol>

      <symbol id="octo" viewBox="0 0 16 16">
        <!-- Icon from GitHub Octicons - https://github.com/primer/octicons/ -->
        <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/>
      </symbol>
    </defs>
  </svg>

  <header>
    <button id="themeToggle" title="Switch Theme" class="theme"></button>
    <a class="github-icon" title="Visit on GitHub" href="https://github.com/catdad/canvas-confetti" aria-label="View source on Github">
      <svg class="icon"><use xlink:href="#octo"></use></svg>
    </a>
  </header>

  <h1>Canvas Confetti</h1>

  <div class="container">
    <div class="group" data-name="cannon">
      <div class="flex-rows">
        <div class="left">
          <h2><a href="#basic" id="basic" class="anchor">Basic Cannon</a></h2>
          <button class="run">
            Run
            <span class="icon">
              <svg class="icon"><use xlink:href="#run"></use></svg>
            </span>
          </button>
        </div>
        <div class="description">
          <p>
            The default mode... just your regular basic average blast of confetti. But it's still
            a little cool, right?
          </p>
        </div>
      </div>
      <div class="editor"></div>
    </div>
  </div>

  <div class="container">
    <div class="group" data-name="random">
      <div class="flex-rows">
        <div class="left">
          <h2><a href="#random" id="random" class="anchor">Random Direction</a></h2>
          <button class="run">
            Run
            <span class="icon">
              <svg class="icon"><use xlink:href="#run"></use></svg>
            </span>
          </button>
        </div>
        <div class="description">
          <p>
            Go crazy with some randomness. Shoot a random amount of confetti in random directions.
            (Go ahead... you know you want to click that button more than once.)
          </p>
        </div>
      </div>
      <div class="editor"></div>
    </div>
  </div>

  <div class="container">
    <div class="group" data-name="realistic">
      <div class="flex-rows">
        <div class="left">
          <h2><a href="#realistic" id="realistic" class="anchor">Realistic Look</a></h2>
          <button class="run">
            Run
            <span class="icon">
              <svg class="icon"><use xlink:href="#run"></use></svg>
            </span>
          </button>
        </div>
        <div class="description">
          <p>
            If you happened to get curious and changed the particle count to 400 or so, you saw
            something disappointing. An even "flattened cone" look to the confetti, making it look
            way too perfect and ruining the illusion. We can fix that by mixing a few effects together.
          </p>
        </div>
      </div>
      <div class="editor"></div>
    </div>
  </div>

  <div class="container">
    <div class="group" data-name="fireworks">
      <div class="flex-rows">
        <div class="left">
          <h2><a href="#fireworks" id="fireworks" class="anchor">Fireworks</a></h2>
          <button class="run">
            Run
            <span class="icon">
              <svg class="icon"><use xlink:href="#run"></use></svg>
            </span>
          </button>
        </div>
        <div class="description">
          <p>
            Why click a button repeatedly when you can have code do it for you? Shoot some firework
            of confetti from the sides of page so you can still read the content in the center.
          </p>
        </div>
      </div>
      <div class="editor"></div>
    </div>
  </div>

  <div class="container">
    <div class="group" data-name="stars">
      <div class="flex-rows">
        <div class="left">
          <h2><a href="#stars" id="stars" class="anchor">Stars</a></h2>
          <button class="run">
            Run
            <span class="icon">
              <svg class="icon"><use xlink:href="#run"></use></svg>
            </span>
          </button>
        </div>
        <div class="description">
          <p>
            You can combine multiple calls to confetti with any settings in order to create
            a more complex effect. Go ahead, combine different shapes, sizes, etc. Stagger them
            for an extra boost of excitement.
          </p>
          <p class="center">✨ Celebrate with a burst of stars! ✨</p>
        </div>
      </div>
      <div class="editor"></div>
    </div>
  </div>

  <div class="container">
    <div class="group" data-name="snow">
      <div class="flex-rows">
        <div class="left">
          <h2><a href="#snow" id="snow" class="anchor">Snow</a></h2>
          <button class="run">
            Run
            <span class="icon">
              <svg class="icon"><use xlink:href="#run"></use></svg>
            </span>
          </button>
        </div>
        <div class="description">
          <p>
            The effect is not limited to crazy rapid fire of confetti though. You can create a
            wintery mood with gently falling particles across the entire page.
          </p>
        </div>
      </div>
      <div class="editor"></div>
    </div>
  </div>

  <div class="container">
    <div class="group" data-name="continuous">
      <div class="flex-rows">
        <div class="left">
          <h2><a href="#continuous" id="continuous" class="anchor">School Pride</a></h2>
          <button class="run">
            Run
            <span class="icon">
              <svg class="icon"><use xlink:href="#run"></use></svg>
            </span>
          </button>
        </div>
        <div class="description">
          <p>
            But if you are into crazy rapid fire of confetti, what could be a better use than
            to show everyone what you are all about? Tell people where you are from with two
            confetti cannons from either side of the page.
          </p>
          <p class="center">🌰 Go Buckeyes! 🌰</p>
        </div>
      </div>
      <div class="editor"></div>
    </div>
  </div>

  <div class="container">
    <div class="group" data-name="paths">
      <div class="flex-rows">
        <div class="left">
          <h2><a href="#paths" id="paths" class="anchor">Custom Shapes</a></h2>
          <button class="run">
            Run
            <span class="icon">
              <svg class="icon"><use xlink:href="#run"></use></svg>
            </span>
          </button>
        </div>
        <div class="description">
          <p>
            Celebrate some holidays with holiday-appropriate shapes! You can use any SVG path
            to make a confetti out of it. Go wild!
          </p>
          <p class="center">🎃🎄💜</p>
        </div>
      </div>
      <div class="editor"></div>
    </div>
  </div>

  <div class="container">
    <div class="group" data-name="emoji">
      <div class="flex-rows">
        <div class="left">
          <h2><a href="#emoji" id="emoji" class="anchor">Emoji</a></h2>
          <button class="run">
            Run
            <span class="icon">
              <svg class="icon"><use xlink:href="#run"></use></svg>
            </span>
          </button>
        </div>
        <div class="description">
          <p>
            Don't know any custom shapes? That's okay, just use emoji instead! That's what they
            are for anyway. I mean... why do they even exist if we weren't supposed to make
            confetti out of them? Think about it.
          </p>
        </div>
      </div>
      <div class="editor"></div>
    </div>
  </div>

  <div class="container">
    <div class="group" data-name="custom">
      <div class="flex-rows">
        <div class="left">
          <h2><a href="#custom-canvas" id="custom-canvas" class="anchor">Custom Canvas</a></h2>
          <button class="run">
            Run
            <span class="icon">
              <svg class="icon"><use xlink:href="#run"></use></svg>
            </span>
          </button>
        </div>
        <div class="description">
          <p>
            But if you just hate confetti all over the place, there's something here for you
            as well. You can limit where the confetti appear by providing your own canvas element.
          </p>
        </div>
      </div>
      <div class="editor"></div>
      <div class="flex-rows">
        <canvas id="my-canvas" class="custom-canvas"></canvas>
      </div>
    </div>
  </div>

  <footer>
    <a href="https://github.com/catdad">
      <span class="icon">
        <svg class="icon"><use xlink:href="#code"></use></svg>
      </span>
      <span> with </span>
      <span class="icon">
        <svg class="icon"><use xlink:href="#heart"></use></svg>
      </span>
      <span> by <b>catdad</b></span>
    </a>
  </footer>

  <script>
    var editors = [];
    var activeTheme = 'dark';
    var currentStep = parseInt(localStorage.getItem('canvas-confetti/theme'), 10) || 0;
    var prefersLightTheme = window.matchMedia && window.matchMedia('(prefers-color-scheme: light)');
    var themes = {
      light: 'ace/theme/xcode',
      dark: 'ace/theme/monokai'
    };

    var getPreferedTheme = function () {
      return prefersLightTheme ? prefersLightTheme.matches ? 'light' : 'dark' : 'dark';
    };

    var setTheme = function (isAuto, theme) {
      if (isAuto) {
        document.body.setAttribute('auto-theme', true);
        activeTheme = getPreferedTheme();
      } else {
        document.body.removeAttribute('auto-theme');
        activeTheme = theme;
      }

      document.body.setAttribute('data-theme', activeTheme);

      editors.forEach(function(editor) {
        editor.setTheme(themes[activeTheme]);
      });
    };

    var updateTheme = function (step) {
      currentStep = step;

      switch (step) {
        case 0:
          setTheme(true);
          prefersLightTheme && prefersLightTheme.addEventListener('change', setTheme);
          break;
        case 1:
        case 2:
          setTheme(false, step === 1 ? 'dark' : 'light');
          prefersLightTheme && prefersLightTheme.removeListener(setTheme);
          break;
      }

      localStorage.setItem('canvas-confetti/theme', currentStep);
    }

    updateTheme(currentStep);

    document.getElementById('themeToggle').addEventListener('click', function (event) {
      updateTheme(++currentStep % 3);
    });

    var modes = {
      cannon: function cannon() {
        confetti({
          particleCount: 100,
          spread: 70,
          origin: { y: 0.6 }
        });
      },
      random: function random() {
        function randomInRange(min, max) {
          return Math.random() * (max - min) + min;
        }

        confetti({
          angle: randomInRange(55, 125),
          spread: randomInRange(50, 70),
          particleCount: randomInRange(50, 100),
          origin: { y: 0.6 }
        });
      },
      realistic: function realistic() {
        var count = 200;
        var defaults = {
          origin: { y: 0.7 }
        };

        function fire(particleRatio, opts) {
          confetti({
            ...defaults,
            ...opts,
            particleCount: Math.floor(count * particleRatio)
          });
        }

        fire(0.25, {
          spread: 26,
          startVelocity: 55,
        });
        fire(0.2, {
          spread: 60,
        });
        fire(0.35, {
          spread: 100,
          decay: 0.91,
          scalar: 0.8
        });
        fire(0.1, {
          spread: 120,
          startVelocity: 25,
          decay: 0.92,
          scalar: 1.2
        });
        fire(0.1, {
          spread: 120,
          startVelocity: 45,
        });
      },
      fireworks: function fireworks() {
        var duration = 15 * 1000;
        var animationEnd = Date.now() + duration;
        var defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 0 };

        function randomInRange(min, max) {
          return Math.random() * (max - min) + min;
        }

        var interval = setInterval(function () {
          var timeLeft = animationEnd - Date.now();

          if (timeLeft <= 0) {
            return clearInterval(interval);
          }

          var particleCount = 50 * (timeLeft / duration);
          // since particles fall down, start a bit higher than random
          confetti({ ...defaults, particleCount, origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 } });
          confetti({ ...defaults, particleCount, origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 } });
        }, 250);
      },
      snow: function snow() {
        var duration = 15 * 1000;
        var animationEnd = Date.now() + duration;
        var skew = 1;

        function randomInRange(min, max) {
          return Math.random() * (max - min) + min;
        }

        (function frame() {
          var timeLeft = animationEnd - Date.now();
          var ticks = Math.max(200, 500 * (timeLeft / duration));
          skew = Math.max(0.8, skew - 0.001);

          confetti({
            particleCount: 1,
            startVelocity: 0,
            ticks: ticks,
            origin: {
              x: Math.random(),
              // since particles fall down, skew start toward the top
              y: (Math.random() * skew) - 0.2
            },
            colors: ['#ffffff'],
            shapes: ['circle'],
            gravity: randomInRange(0.4, 0.6),
            scalar: randomInRange(0.4, 1),
            drift: randomInRange(-0.4, 0.4)
          });

          if (timeLeft > 0) {
            requestAnimationFrame(frame);
          }
        }());
      },
      stars: function stars() {
        var defaults = {
          spread: 360,
          ticks: 50,
          gravity: 0,
          decay: 0.94,
          startVelocity: 30,
          colors: ['FFE400', 'FFBD00', 'E89400', 'FFCA6C', 'FDFFB8']
        };

        function shoot() {
          confetti({
            ...defaults,
            particleCount: 40,
            scalar: 1.2,
            shapes: ['star']
          });

          confetti({
            ...defaults,
            particleCount: 10,
            scalar: 0.75,
            shapes: ['circle']
          });
        }

        setTimeout(shoot, 0);
        setTimeout(shoot, 100);
        setTimeout(shoot, 200);
      },
      continuous: function continuous() {
        var end = Date.now() + (15 * 1000);

        // go Buckeyes!
        var colors = ['#bb0000', '#ffffff'];

        (function frame() {
          confetti({
            particleCount: 2,
            angle: 60,
            spread: 55,
            origin: { x: 0 },
            colors: colors
          });
          confetti({
            particleCount: 2,
            angle: 120,
            spread: 55,
            origin: { x: 1 },
            colors: colors
          });

          if (Date.now() < end) {
            requestAnimationFrame(frame);
          }
        }());
      },
      custom: function() {
        var canvas = document.getElementById('my-canvas');

        // you should  only initialize a canvas once, so save this function
        // we'll save it to the canvas itself for the purpose of this demo
        canvas.confetti = canvas.confetti || confetti.create(canvas, { resize: true });

        canvas.confetti({
          spread: 70,
          origin: { y: 1.2 }
        });
      },
      paths: function() {
        // note: you CAN only use a path for confetti.shapeFrompath(), but for
        // performance reasons it is best to use it once in development and save
        // the result to avoid the performance penalty at runtime

        // pumpkin shape from https://thenounproject.com/icon/pumpkin-5253388/
        var pumpkin = confetti.shapeFromPath({
          path: 'M449.4 142c-5 0-10 .3-15 1a183 183 0 0 0-66.9-19.1V87.5a17.5 17.5 0 1 0-35 0v36.4a183 183 0 0 0-67 19c-4.9-.6-9.9-1-14.8-1C170.3 142 105 219.6 105 315s65.3 173 145.7 173c5 0 10-.3 14.8-1a184.7 184.7 0 0 0 169 0c4.9.7 9.9 1 14.9 1 80.3 0 145.6-77.6 145.6-173s-65.3-173-145.7-173zm-220 138 27.4-40.4a11.6 11.6 0 0 1 16.4-2.7l54.7 40.3a11.3 11.3 0 0 1-7 20.3H239a11.3 11.3 0 0 1-9.6-17.5zM444 383.8l-43.7 17.5a17.7 17.7 0 0 1-13 0l-37.3-15-37.2 15a17.8 17.8 0 0 1-13 0L256 383.8a17.5 17.5 0 0 1 13-32.6l37.3 15 37.2-15c4.2-1.6 8.8-1.6 13 0l37.3 15 37.2-15a17.5 17.5 0 0 1 13 32.6zm17-86.3h-82a11.3 11.3 0 0 1-6.9-20.4l54.7-40.3a11.6 11.6 0 0 1 16.4 2.8l27.4 40.4a11.3 11.3 0 0 1-9.6 17.5z',
          matrix: [0.020491803278688523, 0, 0, 0.020491803278688523, -7.172131147540983, -5.9016393442622945]
        });
        // tree shape from https://thenounproject.com/icon/pine-tree-1471679/
        var tree = confetti.shapeFromPath({
          path: 'M120 240c-41,14 -91,18 -120,1 29,-10 57,-22 81,-40 -18,2 -37,3 -55,-3 25,-14 48,-30 66,-51 -11,5 -26,8 -45,7 20,-14 40,-30 57,-49 -13,1 -26,2 -38,-1 18,-11 35,-25 51,-43 -13,3 -24,5 -35,6 21,-19 40,-41 53,-67 14,26 32,48 54,67 -11,-1 -23,-3 -35,-6 15,18 32,32 51,43 -13,3 -26,2 -38,1 17,19 36,35 56,49 -19,1 -33,-2 -45,-7 19,21 42,37 67,51 -19,6 -37,5 -56,3 25,18 53,30 82,40 -30,17 -79,13 -120,-1l0 41 -31 0 0 -41z',
          matrix: [0.03597122302158273, 0, 0, 0.03597122302158273, -4.856115107913669, -5.071942446043165]
        });
        // heart shape from https://thenounproject.com/icon/heart-1545381/
        var heart = confetti.shapeFromPath({
          path: 'M167 72c19,-38 37,-56 75,-56 42,0 76,33 76,75 0,76 -76,151 -151,227 -76,-76 -151,-151 -151,-227 0,-42 33,-75 75,-75 38,0 57,18 76,56z',
          matrix: [0.03333333333333333, 0, 0, 0.03333333333333333, -5.566666666666666, -5.533333333333333]
        });

        var defaults = {
          scalar: 2,
          spread: 180,
          particleCount: 30,
          origin: { y: -0.1 },
          startVelocity: -35
        };

        confetti({
          ...defaults,
          shapes: [ pumpkin ],
          colors: ['#ff9a00', '#ff7400', '#ff4d00']
        });
        confetti({
          ...defaults,
          shapes: [ tree ],
          colors: ['#8d960f', '#be0f10', '#445404']
        });
        confetti({
          ...defaults,
          shapes: [ heart ],
          colors: ['#f93963', '#a10864', '#ee0b93']
        });
      },
      emoji: function () {
        var scalar = 2;
        var unicorn = confetti.shapeFromText({ text: '🦄', scalar });

        var defaults = {
          spread: 360,
          ticks: 60,
          gravity: 0,
          decay: 0.96,
          startVelocity: 20,
          shapes: [unicorn],
          scalar
        };

        function shoot() {
          confetti({
            ...defaults,
            particleCount: 30
          });

          confetti({
            ...defaults,
            particleCount: 5,
            flat: true
          });

          confetti({
            ...defaults,
            particleCount: 15,
            scalar: scalar / 2,
            shapes: ['circle']
          });
        }

        setTimeout(shoot, 0);
        setTimeout(shoot, 100);
        setTimeout(shoot, 200);
      }
    };

    function pretty(val) {
      return js_beautify(val, { indent_size: 2, brace_style: 'preserve-inline', });
    }

    function getCode(name) {
      // pretty-print the code, since we will use minified code in production
      var code = pretty(modes[name].toString());
      // take out the function wrapper, trim all whitespace
      code = code.split('\n').slice(1).slice(0, -1).map(function (s) {
        return s.trim();
      }).join('\n');
      // pretty-print again
      return pretty(code);
    }

    window.onload = function () {
      [].forEach.call(document.querySelectorAll('.group'), function (group) {
        var name = group.getAttribute('data-name');
        var button = group.querySelector('.run');
        var codeElem = group.querySelector('.editor');

        var editor = ace.edit(codeElem);
        editor.setTheme(themes[activeTheme]);
        editor.session.setMode('ace/mode/javascript');
        editor.session.setUseSoftTabs(true);
        editor.session.setTabSize(2);

        editor.session.setValue(getCode(name));

        var count = editor.session.getLength();

        // set height so that all code is visible
        codeElem.style.minHeight = (14 * count) + 1 + 'px';
        codeElem.style.height = (count) + 'rem';

        button.onclick = function (ev) {
          // stop mobile browsers from zooming when clicking
          // buttons repeatedly really fast
          ev.preventDefault();

          try {
            eval(editor.getValue());
          } catch (e) {
            console.error(e);
          }
        };

        editors.push(editor);
      });
    };
  </script>

  <script>
    // render favicon live, because why not
    addEventListener("load", (event) => {
      const image = confetti.shapeFromText('🎊', { scalar: 512/10 });
      const canvas = new OffscreenCanvas(image.bitmap.width, image.bitmap.height);
      const ctx = canvas.getContext('bitmaprenderer');
      ctx.transferFromImageBitmap(image.bitmap);

      canvas.convertToBlob().then(blob => {
        const icon = document.getElementById('favicon');
        icon.setAttribute('href', URL.createObjectURL(blob));
      });
    });
  </script>

  <script src="/analytics.js" async></script>
</body>
</html>


================================================
FILE: package.json
================================================
{
  "name": "canvas-confetti",
  "version": "1.9.4",
  "description": "performant confetti animation in the browser",
  "main": "src/confetti.js",
  "module": "dist/confetti.module.mjs",
  "jsdelivr": "dist/confetti.browser.js",
  "scripts": {
    "build": "node build/build.js",
    "browserify": "browserify --entry src/confetti.js --outfile temp/confetti.bundle.js --standalone confetti",
    "minify": "terser --compress --mangle -o temp/confetti.min.js -- dist/confetti.browser.js",
    "pretest": "npm run build -s && npm run browserify -s && npm run -s minify",
    "test": "cd test && ava --verbose --serial",
    "lint": "eslint src/**/*.js test/**/*.js build/**/*.js",
    "dev": "node build/serve.js",
    "devtest": "cross-env CONFETTI_SHOW=1 npm test",
    "citest": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/catdad/canvas-confetti.git"
  },
  "author": "Kiril Vatev <vatev.1@gmail.com>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/catdad/canvas-confetti/issues"
  },
  "homepage": "https://github.com/catdad/canvas-confetti#readme",
  "devDependencies": {
    "ava": "2.4.0",
    "babel-eslint": "^8.2.1",
    "browserify": "^15.2.0",
    "cross-env": "^5.1.3",
    "eslint": "^8.57.1",
    "eslint-plugin-ava": "^13.2.0",
    "jimp": "^0.2.28",
    "puppeteer": "^19.11.1",
    "rootrequire": "^1.0.0",
    "send": "^0.16.1",
    "terser": "^3.14.1"
  },
  "keywords": [
    "canvas",
    "confetti",
    "animation",
    "burst",
    "fireworks",
    "snow",
    "particles"
  ],
  "funding": {
    "type": "donate",
    "url": "https://www.paypal.me/kirilvatev"
  }
}


================================================
FILE: src/confetti.js
================================================
/* globals Map */

(function main(global, module, isWorker, workerSize) {
  var canUseWorker = !!(
    global.Worker &&
    global.Blob &&
    global.Promise &&
    global.OffscreenCanvas &&
    global.OffscreenCanvasRenderingContext2D &&
    global.HTMLCanvasElement &&
    global.HTMLCanvasElement.prototype.transferControlToOffscreen &&
    global.URL &&
    global.URL.createObjectURL);

  var canUsePaths = typeof Path2D === 'function' && typeof DOMMatrix === 'function';
  var canDrawBitmap = (function () {
    // this mostly supports ssr
    if (!global.OffscreenCanvas) {
      return false;
    }

    try {
      var canvas = new OffscreenCanvas(1, 1);
      var ctx = canvas.getContext('2d');
      ctx.fillRect(0, 0, 1, 1);
      var bitmap = canvas.transferToImageBitmap();
      ctx.createPattern(bitmap, 'no-repeat');
    } catch (e) {
      return false;
    }

    return true;
  })();

  function noop() {}

  // create a promise if it exists, otherwise, just
  // call the function directly
  function promise(func) {
    var ModulePromise = module.exports.Promise;
    var Prom = ModulePromise !== void 0 ? ModulePromise : global.Promise;

    if (typeof Prom === 'function') {
      return new Prom(func);
    }

    func(noop, noop);

    return null;
  }

  var bitmapMapper = (function (skipTransform, map) {
    // see https://github.com/catdad/canvas-confetti/issues/209
    // creating canvases is actually pretty expensive, so we should create a
    // 1:1 map for bitmap:canvas, so that we can animate the confetti in
    // a performant manner, but also not store them forever so that we don't
    // have a memory leak
    return {
      transform: function(bitmap) {
        if (skipTransform) {
          return bitmap;
        }

        if (map.has(bitmap)) {
          return map.get(bitmap);
        }

        var canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
        var ctx = canvas.getContext('2d');
        ctx.drawImage(bitmap, 0, 0);

        map.set(bitmap, canvas);

        return canvas;
      },
      clear: function () {
        map.clear();
      }
    };
  })(canDrawBitmap, new Map());

  var raf = (function () {
    var TIME = Math.floor(1000 / 60);
    var frame, cancel;
    var frames = {};
    var lastFrameTime = 0;

    if (typeof requestAnimationFrame === 'function' && typeof cancelAnimationFrame === 'function') {
      frame = function (cb) {
        var id = Math.random();

        frames[id] = requestAnimationFrame(function onFrame(time) {
          if (lastFrameTime === time || lastFrameTime + TIME - 1 < time) {
            lastFrameTime = time;
            delete frames[id];

            cb();
          } else {
            frames[id] = requestAnimationFrame(onFrame);
          }
        });

        return id;
      };
      cancel = function (id) {
        if (frames[id]) {
          cancelAnimationFrame(frames[id]);
        }
      };
    } else {
      frame = function (cb) {
        return setTimeout(cb, TIME);
      };
      cancel = function (timer) {
        return clearTimeout(timer);
      };
    }

    return { frame: frame, cancel: cancel };
  }());

  var getWorker = (function () {
    var worker;
    var prom;
    var resolves = {};

    function decorate(worker) {
      function execute(options, callback) {
        worker.postMessage({ options: options || {}, callback: callback });
      }
      worker.init = function initWorker(canvas) {
        var offscreen = canvas.transferControlToOffscreen();
        worker.postMessage({ canvas: offscreen }, [offscreen]);
      };

      worker.fire = function fireWorker(options, size, done) {
        if (prom) {
          execute(options, null);
          return prom;
        }

        var id = Math.random().toString(36).slice(2);

        prom = promise(function (resolve) {
          function workerDone(msg) {
            if (msg.data.callback !== id) {
              return;
            }

            delete resolves[id];
            worker.removeEventListener('message', workerDone);

            prom = null;

            bitmapMapper.clear();

            done();
            resolve();
          }

          worker.addEventListener('message', workerDone);
          execute(options, id);

          resolves[id] = workerDone.bind(null, { data: { callback: id }});
        });

        return prom;
      };

      worker.reset = function resetWorker() {
        worker.postMessage({ reset: true });

        for (var id in resolves) {
          resolves[id]();
          delete resolves[id];
        }
      };
    }

    return function () {
      if (worker) {
        return worker;
      }

      if (!isWorker && canUseWorker) {
        var code = [
          'var CONFETTI, SIZE = {}, module = {};',
          '(' + main.toString() + ')(this, module, true, SIZE);',
          'onmessage = function(msg) {',
          '  if (msg.data.options) {',
          '    CONFETTI(msg.data.options).then(function () {',
          '      if (msg.data.callback) {',
          '        postMessage({ callback: msg.data.callback });',
          '      }',
          '    });',
          '  } else if (msg.data.reset) {',
          '    CONFETTI && CONFETTI.reset();',
          '  } else if (msg.data.resize) {',
          '    SIZE.width = msg.data.resize.width;',
          '    SIZE.height = msg.data.resize.height;',
          '  } else if (msg.data.canvas) {',
          '    SIZE.width = msg.data.canvas.width;',
          '    SIZE.height = msg.data.canvas.height;',
          '    CONFETTI = module.exports.create(msg.data.canvas);',
          '  }',
          '}',
        ].join('\n');
        try {
          worker = new Worker(URL.createObjectURL(new Blob([code])));
        } catch (e) {
          // eslint-disable-next-line no-console
          typeof console !== 'undefined' && typeof console.warn === 'function' ? console.warn('🎊 Could not load worker', e) : null;

          return null;
        }

        decorate(worker);
      }

      return worker;
    };
  })();

  var defaults = {
    particleCount: 50,
    angle: 90,
    spread: 45,
    startVelocity: 45,
    decay: 0.9,
    gravity: 1,
    drift: 0,
    ticks: 200,
    x: 0.5,
    y: 0.5,
    shapes: ['square', 'circle'],
    zIndex: 100,
    colors: [
      '#26ccff',
      '#a25afd',
      '#ff5e7e',
      '#88ff5a',
      '#fcff42',
      '#ffa62d',
      '#ff36ff'
    ],
    // probably should be true, but back-compat
    disableForReducedMotion: false,
    scalar: 1
  };

  function convert(val, transform) {
    return transform ? transform(val) : val;
  }

  function isOk(val) {
    return !(val === null || val === undefined);
  }

  function prop(options, name, transform) {
    return convert(
      options && isOk(options[name]) ? options[name] : defaults[name],
      transform
    );
  }

  function onlyPositiveInt(number){
    return number < 0 ? 0 : Math.floor(number);
  }

  function randomInt(min, max) {
    // [min, max)
    return Math.floor(Math.random() * (max - min)) + min;
  }

  function toDecimal(str) {
    return parseInt(str, 16);
  }

  function colorsToRgb(colors) {
    return colors.map(hexToRgb);
  }

  function hexToRgb(str) {
    var val = String(str).replace(/[^0-9a-f]/gi, '');

    if (val.length < 6) {
        val = val[0]+val[0]+val[1]+val[1]+val[2]+val[2];
    }

    return {
      r: toDecimal(val.substring(0,2)),
      g: toDecimal(val.substring(2,4)),
      b: toDecimal(val.substring(4,6))
    };
  }

  function getOrigin(options) {
    var origin = prop(options, 'origin', Object);
    origin.x = prop(origin, 'x', Number);
    origin.y = prop(origin, 'y', Number);

    return origin;
  }

  function setCanvasWindowSize(canvas) {
    canvas.width = document.documentElement.clientWidth;
    canvas.height = document.documentElement.clientHeight;
  }

  function setCanvasRectSize(canvas) {
    var rect = canvas.getBoundingClientRect();
    canvas.width = rect.width;
    canvas.height = rect.height;
  }

  function getCanvas(zIndex) {
    var canvas = document.createElement('canvas');

    canvas.style.position = 'fixed';
    canvas.style.top = '0px';
    canvas.style.left = '0px';
    canvas.style.pointerEvents = 'none';
    canvas.style.zIndex = zIndex;

    return canvas;
  }

  function ellipse(context, x, y, radiusX, radiusY, rotation, startAngle, endAngle, antiClockwise) {
    context.save();
    context.translate(x, y);
    context.rotate(rotation);
    context.scale(radiusX, radiusY);
    context.arc(0, 0, 1, startAngle, endAngle, antiClockwise);
    context.restore();
  }

  function randomPhysics(opts) {
    var radAngle = opts.angle * (Math.PI / 180);
    var radSpread = opts.spread * (Math.PI / 180);

    return {
      x: opts.x,
      y: opts.y,
      wobble: Math.random() * 10,
      wobbleSpeed: Math.min(0.11, Math.random() * 0.1 + 0.05),
      velocity: (opts.startVelocity * 0.5) + (Math.random() * opts.startVelocity),
      angle2D: -radAngle + ((0.5 * radSpread) - (Math.random() * radSpread)),
      tiltAngle: (Math.random() * (0.75 - 0.25) + 0.25) * Math.PI,
      color: opts.color,
      shape: opts.shape,
      tick: 0,
      totalTicks: opts.ticks,
      decay: opts.decay,
      drift: opts.drift,
      random: Math.random() + 2,
      tiltSin: 0,
      tiltCos: 0,
      wobbleX: 0,
      wobbleY: 0,
      gravity: opts.gravity * 3,
      ovalScalar: 0.6,
      scalar: opts.scalar,
      flat: opts.flat
    };
  }

  function updateFetti(context, fetti) {
    fetti.x += Math.cos(fetti.angle2D) * fetti.velocity + fetti.drift;
    fetti.y += Math.sin(fetti.angle2D) * fetti.velocity + fetti.gravity;
    fetti.velocity *= fetti.decay;

    if (fetti.flat) {
      fetti.wobble = 0;
      fetti.wobbleX = fetti.x + (10 * fetti.scalar);
      fetti.wobbleY = fetti.y + (10 * fetti.scalar);

      fetti.tiltSin = 0;
      fetti.tiltCos = 0;
      fetti.random = 1;
    } else {
      fetti.wobble += fetti.wobbleSpeed;
      fetti.wobbleX = fetti.x + ((10 * fetti.scalar) * Math.cos(fetti.wobble));
      fetti.wobbleY = fetti.y + ((10 * fetti.scalar) * Math.sin(fetti.wobble));

      fetti.tiltAngle += 0.1;
      fetti.tiltSin = Math.sin(fetti.tiltAngle);
      fetti.tiltCos = Math.cos(fetti.tiltAngle);
      fetti.random = Math.random() + 2;
    }

    var progress = (fetti.tick++) / fetti.totalTicks;

    var x1 = fetti.x + (fetti.random * fetti.tiltCos);
    var y1 = fetti.y + (fetti.random * fetti.tiltSin);
    var x2 = fetti.wobbleX + (fetti.random * fetti.tiltCos);
    var y2 = fetti.wobbleY + (fetti.random * fetti.tiltSin);

    context.fillStyle = 'rgba(' + fetti.color.r + ', ' + fetti.color.g + ', ' + fetti.color.b + ', ' + (1 - progress) + ')';

    context.beginPath();

    if (canUsePaths && fetti.shape.type === 'path' && typeof fetti.shape.path === 'string' && Array.isArray(fetti.shape.matrix)) {
      context.fill(transformPath2D(
        fetti.shape.path,
        fetti.shape.matrix,
        fetti.x,
        fetti.y,
        Math.abs(x2 - x1) * 0.1,
        Math.abs(y2 - y1) * 0.1,
        Math.PI / 10 * fetti.wobble
      ));
    } else if (fetti.shape.type === 'bitmap') {
      var rotation = Math.PI / 10 * fetti.wobble;
      var scaleX = Math.abs(x2 - x1) * 0.1;
      var scaleY = Math.abs(y2 - y1) * 0.1;
      var width = fetti.shape.bitmap.width * fetti.scalar;
      var height = fetti.shape.bitmap.height * fetti.scalar;

      var matrix = new DOMMatrix([
        Math.cos(rotation) * scaleX,
        Math.sin(rotation) * scaleX,
        -Math.sin(rotation) * scaleY,
        Math.cos(rotation) * scaleY,
        fetti.x,
        fetti.y
      ]);

      // apply the transform matrix from the confetti shape
      matrix.multiplySelf(new DOMMatrix(fetti.shape.matrix));

      var pattern = context.createPattern(bitmapMapper.transform(fetti.shape.bitmap), 'no-repeat');
      pattern.setTransform(matrix);

      context.globalAlpha = (1 - progress);
      context.fillStyle = pattern;
      context.fillRect(
        fetti.x - (width / 2),
        fetti.y - (height / 2),
        width,
        height
      );
      context.globalAlpha = 1;
    } else if (fetti.shape === 'circle') {
      context.ellipse ?
        context.ellipse(fetti.x, fetti.y, Math.abs(x2 - x1) * fetti.ovalScalar, Math.abs(y2 - y1) * fetti.ovalScalar, Math.PI / 10 * fetti.wobble, 0, 2 * Math.PI) :
        ellipse(context, fetti.x, fetti.y, Math.abs(x2 - x1) * fetti.ovalScalar, Math.abs(y2 - y1) * fetti.ovalScalar, Math.PI / 10 * fetti.wobble, 0, 2 * Math.PI);
    } else if (fetti.shape === 'star') {
      var rot = Math.PI / 2 * 3;
      var innerRadius = 4 * fetti.scalar;
      var outerRadius = 8 * fetti.scalar;
      var x = fetti.x;
      var y = fetti.y;
      var spikes = 5;
      var step = Math.PI / spikes;

      while (spikes--) {
        x = fetti.x + Math.cos(rot) * outerRadius;
        y = fetti.y + Math.sin(rot) * outerRadius;
        context.lineTo(x, y);
        rot += step;

        x = fetti.x + Math.cos(rot) * innerRadius;
        y = fetti.y + Math.sin(rot) * innerRadius;
        context.lineTo(x, y);
        rot += step;
      }
    } else {
      context.moveTo(Math.floor(fetti.x), Math.floor(fetti.y));
      context.lineTo(Math.floor(fetti.wobbleX), Math.floor(y1));
      context.lineTo(Math.floor(x2), Math.floor(y2));
      context.lineTo(Math.floor(x1), Math.floor(fetti.wobbleY));
    }

    context.closePath();
    context.fill();

    return fetti.tick < fetti.totalTicks;
  }

  function animate(canvas, fettis, resizer, size, done) {
    var animatingFettis = fettis.slice();
    var context = canvas.getContext('2d');
    var animationFrame;
    var destroy;

    var prom = promise(function (resolve) {
      function onDone() {
        animationFrame = destroy = null;

        context.clearRect(0, 0, size.width, size.height);
        bitmapMapper.clear();

        done();
        resolve();
      }

      function update() {
        if (isWorker && !(size.width === workerSize.width && size.height === workerSize.height)) {
          size.width = canvas.width = workerSize.width;
          size.height = canvas.height = workerSize.height;
        }

        if (!size.width && !size.height) {
          resizer(canvas);
          size.width = canvas.width;
          size.height = canvas.height;
        }

        context.clearRect(0, 0, size.width, size.height);

        animatingFettis = animatingFettis.filter(function (fetti) {
          return updateFetti(context, fetti);
        });

        if (animatingFettis.length) {
          animationFrame = raf.frame(update);
        } else {
          onDone();
        }
      }

      animationFrame = raf.frame(update);
      destroy = onDone;
    });

    return {
      addFettis: function (fettis) {
        animatingFettis = animatingFettis.concat(fettis);

        return prom;
      },
      canvas: canvas,
      promise: prom,
      reset: function () {
        if (animationFrame) {
          raf.cancel(animationFrame);
        }

        if (destroy) {
          destroy();
        }
      }
    };
  }

  function confettiCannon(canvas, globalOpts) {
    var isLibCanvas = !canvas;
    var allowResize = !!prop(globalOpts || {}, 'resize');
    var hasResizeEventRegistered = false;
    var globalDisableForReducedMotion = prop(globalOpts, 'disableForReducedMotion', Boolean);
    var shouldUseWorker = canUseWorker && !!prop(globalOpts || {}, 'useWorker');
    var worker = shouldUseWorker ? getWorker() : null;
    var resizer = isLibCanvas ? setCanvasWindowSize : setCanvasRectSize;
    var initialized = (canvas && worker) ? !!canvas.__confetti_initialized : false;
    var preferLessMotion = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion)').matches;
    var animationObj;

    function fireLocal(options, size, done) {
      var particleCount = prop(options, 'particleCount', onlyPositiveInt);
      var angle = prop(options, 'angle', Number);
      var spread = prop(options, 'spread', Number);
      var startVelocity = prop(options, 'startVelocity', Number);
      var decay = prop(options, 'decay', Number);
      var gravity = prop(options, 'gravity', Number);
      var drift = prop(options, 'drift', Number);
      var colors = prop(options, 'colors', colorsToRgb);
      var ticks = prop(options, 'ticks', Number);
      var shapes = prop(options, 'shapes');
      var scalar = prop(options, 'scalar');
      var flat = !!prop(options, 'flat');
      var origin = getOrigin(options);

      var temp = particleCount;
      var fettis = [];

      var startX = canvas.width * origin.x;
      var startY = canvas.height * origin.y;

      while (temp--) {
        fettis.push(
          randomPhysics({
            x: startX,
            y: startY,
            angle: angle,
            spread: spread,
            startVelocity: startVelocity,
            color: colors[temp % colors.length],
            shape: shapes[randomInt(0, shapes.length)],
            ticks: ticks,
            decay: decay,
            gravity: gravity,
            drift: drift,
            scalar: scalar,
            flat: flat
          })
        );
      }

      // if we have a previous canvas already animating,
      // add to it
      if (animationObj) {
        return animationObj.addFettis(fettis);
      }

      animationObj = animate(canvas, fettis, resizer, size , done);

      return animationObj.promise;
    }

    function fire(options) {
      var disableForReducedMotion = globalDisableForReducedMotion || prop(options, 'disableForReducedMotion', Boolean);
      var zIndex = prop(options, 'zIndex', Number);

      if (disableForReducedMotion && preferLessMotion) {
        return promise(function (resolve) {
          resolve();
        });
      }

      if (isLibCanvas && animationObj) {
        // use existing canvas from in-progress animation
        canvas = animationObj.canvas;
      } else if (isLibCanvas && !canvas) {
        // create and initialize a new canvas
        canvas = getCanvas(zIndex);
        document.body.appendChild(canvas);
      }

      if (allowResize && !initialized) {
        // initialize the size of a user-supplied canvas
        resizer(canvas);
      }

      var size = {
        width: canvas.width,
        height: canvas.height
      };

      if (worker && !initialized) {
        worker.init(canvas);
      }

      initialized = true;

      if (worker) {
        canvas.__confetti_initialized = true;
      }

      function onResize() {
        if (worker) {
          // TODO this really shouldn't be immediate, because it is expensive
          var obj = {
            getBoundingClientRect: function () {
              if (!isLibCanvas) {
                return canvas.getBoundingClientRect();
              }
            }
          };

          resizer(obj);

          worker.postMessage({
            resize: {
              width: obj.width,
              height: obj.height
            }
          });
          return;
        }

        // don't actually query the size here, since this
        // can execute frequently and rapidly
        size.width = size.height = null;
      }

      function done() {
        animationObj = null;

        if (allowResize) {
          hasResizeEventRegistered = false;
          global.removeEventListener('resize', onResize);
        }

        if (isLibCanvas && canvas) {
          if (document.body.contains(canvas)) {
            document.body.removeChild(canvas);
          }
          canvas = null;
          initialized = false;
        }
      }

      if (allowResize && !hasResizeEventRegistered) {
        hasResizeEventRegistered = true;
        global.addEventListener('resize', onResize, false);
      }

      if (worker) {
        return worker.fire(options, size, done);
      }

      return fireLocal(options, size, done);
    }

    fire.reset = function () {
      if (worker) {
        worker.reset();
      }

      if (animationObj) {
        animationObj.reset();
      }
    };

    return fire;
  }

  // Make default export lazy to defer worker creation until called.
  var defaultFire;
  function getDefaultFire() {
    if (!defaultFire) {
      defaultFire = confettiCannon(null, { useWorker: true, resize: true });
    }
    return defaultFire;
  }

  function transformPath2D(pathString, pathMatrix, x, y, scaleX, scaleY, rotation) {
    var path2d = new Path2D(pathString);

    var t1 = new Path2D();
    t1.addPath(path2d, new DOMMatrix(pathMatrix));

    var t2 = new Path2D();
    // see https://developer.mozilla.org/en-US/docs/Web/API/DOMMatrix/DOMMatrix
    t2.addPath(t1, new DOMMatrix([
      Math.cos(rotation) * scaleX,
      Math.sin(rotation) * scaleX,
      -Math.sin(rotation) * scaleY,
      Math.cos(rotation) * scaleY,
      x,
      y
    ]));

    return t2;
  }

  function shapeFromPath(pathData) {
    if (!canUsePaths) {
      throw new Error('path confetti are not supported in this browser');
    }

    var path, matrix;

    if (typeof pathData === 'string') {
      path = pathData;
    } else {
      path = pathData.path;
      matrix = pathData.matrix;
    }

    var path2d = new Path2D(path);
    var tempCanvas = document.createElement('canvas');
    var tempCtx = tempCanvas.getContext('2d');

    if (!matrix) {
      // attempt to figure out the width of the path, up to 1000x1000
      var maxSize = 1000;
      var minX = maxSize;
      var minY = maxSize;
      var maxX = 0;
      var maxY = 0;
      var width, height;

      // do some line skipping... this is faster than checking
      // every pixel and will be mostly still correct
      for (var x = 0; x < maxSize; x += 2) {
        for (var y = 0; y < maxSize; y += 2) {
          if (tempCtx.isPointInPath(path2d, x, y, 'nonzero')) {
            minX = Math.min(minX, x);
            minY = Math.min(minY, y);
            maxX = Math.max(maxX, x);
            maxY = Math.max(maxY, y);
          }
        }
      }

      width = maxX - minX;
      height = maxY - minY;

      var maxDesiredSize = 10;
      var scale = Math.min(maxDesiredSize/width, maxDesiredSize/height);

      matrix = [
        scale, 0, 0, scale,
        -Math.round((width/2) + minX) * scale,
        -Math.round((height/2) + minY) * scale
      ];
    }

    return {
      type: 'path',
      path: path,
      matrix: matrix
    };
  }

  function shapeFromText(textData) {
    var text,
        scalar = 1,
        color = '#000000',
        // see https://nolanlawson.com/2022/04/08/the-struggle-of-using-native-emoji-on-the-web/
        fontFamily = '"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';

    if (typeof textData === 'string') {
      text = textData;
    } else {
      text = textData.text;
      scalar = 'scalar' in textData ? textData.scalar : scalar;
      fontFamily = 'fontFamily' in textData ? textData.fontFamily : fontFamily;
      color = 'color' in textData ? textData.color : color;
    }

    // all other confetti are 10 pixels,
    // so this pixel size is the de-facto 100% scale confetti
    var fontSize = 10 * scalar;
    var font = '' + fontSize + 'px ' + fontFamily;

    var canvas = new OffscreenCanvas(fontSize, fontSize);
    var ctx = canvas.getContext('2d');

    ctx.font = font;
    var size = ctx.measureText(text);
    var width = Math.ceil(size.actualBoundingBoxRight + size.actualBoundingBoxLeft);
    var height = Math.ceil(size.actualBoundingBoxAscent + size.actualBoundingBoxDescent);

    var padding = 2;
    var x = size.actualBoundingBoxLeft + padding;
    var y = size.actualBoundingBoxAscent + padding;
    width += padding + padding;
    height += padding + padding;

    canvas = new OffscreenCanvas(width, height);
    ctx = canvas.getContext('2d');
    ctx.font = font;
    ctx.fillStyle = color;

    ctx.fillText(text, x, y);

    var scale = 1 / scalar;

    return {
      type: 'bitmap',
      // TODO these probably need to be transfered for workers
      bitmap: canvas.transferToImageBitmap(),
      matrix: [scale, 0, 0, scale, -width * scale / 2, -height * scale / 2]
    };
  }

  module.exports = function() {
    return getDefaultFire().apply(this, arguments);
  };
  module.exports.reset = function() {
    getDefaultFire().reset();
  };
  module.exports.create = confettiCannon;
  module.exports.shapeFromPath = shapeFromPath;
  module.exports.shapeFromText = shapeFromText;
}((function () {
  if (typeof window !== 'undefined') {
    return window;
  }

  if (typeof self !== 'undefined') {
    return self;
  }

  return this || {};
})(), module, false));


================================================
FILE: test/.eslintrc.yml
================================================
extends:
  - plugin:ava/recommended
env:
  es6: true
  node: true
  browser: false
parser: babel-eslint
parserOptions:
  sourceType: module
  ecmaVersion: 6
  ecmaFeatures:
    modules: true
plugins:
  - ava


================================================
FILE: test/index.test.js
================================================
import fs from 'fs';
import http from 'http';
import path from 'path';
import { promisify } from 'util';

import test from 'ava';
import puppeteer from 'puppeteer';
import send from 'send';
import root from 'rootrequire';
import jimp from 'jimp';

const PORT = 9999;
const width = 500;
const height = 500;

const args = ['--disable-background-timer-throttling'];

// Docker-based CIs need this disabled
// https://github.com/Quramy/puppeteer-example/blob/c28a5aa52fe3968c2d6cfca362ec28c36963be26/README.md#with-docker-based-ci-services
if (process.env.CI) {
  args.push('--no-sandbox', '--disable-setuid-sandbox');
}

const headless = (process.env.CI || !('CONFETTI_SHOW' in process.env)) ? 'new' : false;

const mkdir = async (dir) => {
  return promisify(fs.mkdir)(dir)
    .then(() => Promise.resolve())
    .catch(err => {
      if (err.code === 'EEXIST') {
        return Promise.resolve();
      }

      return Promise.reject(err);
    });
};

const testServer = (function startServer() {
  let server;

  return function () {
    return new Promise((resolve) => {
      if (server) {
        return resolve(server);
      }

      server = http.createServer(function (req, res) {
        var file = path.resolve(root, req.url.slice(1));
        send(req, file).pipe(res);
      }).listen(PORT, () => {
        resolve(server);
      });
    });
  };
}());

const testBrowser = (() => {
  let browser;

  return function () {
    if (browser) {
      return Promise.resolve(browser);
    }

    return puppeteer.launch({
      headless,
      args
    }).then(thisBrowser => {
      browser = thisBrowser;
      return Promise.resolve(browser);
    });
  };
})();

const testPage = async () => {
  const browser = await testBrowser();
  const page = await browser.newPage();
  await page.setViewport({ width, height });

  // eslint-disable-next-line no-console
  page.on('pageerror', err => console.error(err));
  // eslint-disable-next-line no-console
  page.on('console', msg => console.log(msg.text()));

  return page;
};

const fixturePage = async (urlPath = 'fixtures/page.html') => {
  const page = await testPage();
  await page.goto(`http://localhost:${PORT}/${urlPath}`);

  return page;
};

// eslint-disable-next-line no-unused-vars
const sleep = (time) => {
  return new Promise(resolve => {
    setTimeout(() => resolve(), time);
  });
};

const createBuffer = (data, format) => {
  try {
    return Buffer.from(data, format);
  } catch(e) {
    return new Buffer(data, format);
  }
};

function serializeConfettiOptions(opts) {
  let serializedOpts = opts ? JSON.stringify(opts) : '';

  if (opts && opts.shapes && Array.isArray(opts.shapes)) {
    const { shapes, ...rest } = opts;

    const serializedShapes = shapes.map(shape => {
      if (typeof shape === 'function') {
        return `(${shape.toString()})()`;
      }

      return JSON.stringify(shape);
    });

    serializedOpts = `{
      ...${JSON.stringify(rest)},
      shapes: [${serializedShapes.join(', ')}]
    }`;
  }

  return serializedOpts;
}

function confetti(opts, wait = false, funcName = 'confetti') {
  const serializedOpts = serializeConfettiOptions(opts);

  return `
${wait ? '' : `${funcName}.Promise = null;`}
${funcName}(${serializedOpts});
`;
}

const base64ToBuffer = base64png => createBuffer(base64png.replace(/data:image\/png;base64,/, ''), 'base64');

async function confettiImage(page, opts = {}, funcName = 'confetti') {
  const serializedOpts = serializeConfettiOptions(opts);
  const base64png = await page.evaluate(`
    ${funcName}(${serializedOpts});
    new Promise(function (resolve, reject) {
      setTimeout(function () {
        var canvas = document.querySelector('canvas');
        return resolve(canvas.toDataURL('image/png'));
      }, 200);
    });
  `);

  return base64ToBuffer(base64png);
}

function hex(n) {
  const pad = (n) => {
    while (n.length < 2) {
      n = '0'+n;
    }
    return n;
  };

  return pad(n.toString(16));
}

const getImageBuffer = async (image) => {
  return await promisify(image.getBuffer.bind(image))(jimp.MIME_PNG);
};

const readImage = async (buffer) => {
  return Buffer.isBuffer(buffer) ? await jimp.read(buffer) : buffer;
};

const uniqueColors = async (buffer) => {
  const image = await readImage(buffer);
  const pixels = new Set();

  image.scan(0, 0, image.bitmap.width, image.bitmap.height, (x, y, idx) => {
    const r = image.bitmap.data[idx + 0];
    const g = image.bitmap.data[idx + 1];
    const b = image.bitmap.data[idx + 2];

    pixels.add(`#${hex(r)}${hex(g)}${hex(b)}`);
  });

  return Array.from(pixels).sort();
};

const uniqueColorsBySide = async (buffer) => {
  const image = await readImage(buffer);

  const { width, height } = image.bitmap;
  const leftImage = image.clone().crop(0, 0, width / 2, height);
  const rightImage = image.clone().crop(width / 2, 0, width/2, height);

  return {
    left: await uniqueColors(leftImage),
    right: await uniqueColors(rightImage)
  };
};

const totalPixels = async(buffer) => {
  const image = await readImage(buffer);
  let pixels = 0;
  image.scan(0, 0, image.bitmap.width, image.bitmap.height, (x, y, idx) => {
    const r = image.bitmap.data[idx + 0];
    const g = image.bitmap.data[idx + 1];
    const b = image.bitmap.data[idx + 2];

    if (r === 255 && g === 255 && b === 255) { return; }

    pixels++;
  });
  return pixels;
};

const removeOpacity = async (buffer) => {
  const image = await readImage(buffer);
  image.rgba(false).background(0xFFFFFFFF);
  var opaqueBuffer = await promisify(image.getBuffer.bind(image))(jimp.MIME_PNG);

  return await jimp.read(opaqueBuffer);
};

const reduceImg = async (buffer, opaque = true) => {
  const image = opaque ?
    await removeOpacity(buffer) :
    await readImage(buffer);

  // basically dialate the crap out of everything
  image.blur(2);
  image.posterize(1);

  return image;
};

const emptyImg = function (width, height) {
  return new Promise((resolve, reject) => {
    new jimp(width, height, (err, img) => {
      if (err) {
        return reject(err);
      }

      resolve(img);
    });
  });
};

test.before(async () => {
  await mkdir('./shots');
  await testServer();
  await testBrowser();
});

test.after(async () => {
  const browser = await testBrowser();
  await browser.close();

  const server = await testServer();
  await new Promise(resolve => {
    server.close(() => resolve());
  });
});

// hack to get the status of a test, until AVA implements this
// https://github.com/avajs/ava/issues/840
test.beforeEach((t) => {
  t.context.page = null;
  t.context.passing = false;
});
test.afterEach((t) => {
  t.context.passing = true;
});

test.afterEach.always(async t => {
  if (t.context.page) {
    await t.context.page.close();
  }

  if (t.context.passing && !process.env['CONFETTI_SHOW']) {
    return;
  }

  // this is allowed, but still needs the eslint plugin to be updated
  // https://github.com/avajs/eslint-plugin-ava/issues/176
  // eslint-disable-next-line ava/use-t-well
  const name = t.title.replace(/^afterEach\.always hook for /, '');

  // save the raw buffer image, if one is present
  if (t.context.buffer) {
    await promisify(fs.writeFile)(`shots/${name}.original.png`, t.context.buffer);
  }

  // save the simplified/tested image, if one is present
  if (t.context.image) {
    await promisify(t.context.image.write.bind(t.context.image))(`shots/${name}.reduced.png`);
  }
});

/*
 * Image-based tests
 */

test('shoots default confetti', async t => {
  const page = t.context.page = await fixturePage();

  t.context.buffer = await confettiImage(page);
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColors(t.context.image);

  t.true(pixels.length >= 7);
  t.true(pixels.length <= 8);
});

test('shoots red confetti', async t => {
  const page = t.context.page = await fixturePage();

  t.context.buffer = await confettiImage(page, {
    colors: ['#ff0000']
  });
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColors(t.context.image);

  t.deepEqual(pixels, ['#ff0000', '#ffffff']);
});

test('shoots blue confetti', async t => {
  const page = t.context.page = await fixturePage();

  t.context.buffer = await confettiImage(page, {
    colors: ['#0000ff']
  });
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColors(t.context.image);

  t.deepEqual(pixels, ['#0000ff', '#ffffff']);
});

test('shoots circle confetti', async t => {
  const page = t.context.page = await fixturePage();

  t.context.buffer = await confettiImage(page, {
    colors: ['#0000ff'],
    shapes: ['circle']
  });
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColors(t.context.image);

  t.deepEqual(pixels, ['#0000ff', '#ffffff']);
});

test('shoots star confetti', async t => {
  const page = t.context.page = await fixturePage();

  t.context.buffer = await confettiImage(page, {
    colors: ['#0000ff'],
    shapes: ['star']
  });
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColors(t.context.image);

  t.deepEqual(pixels, ['#0000ff', '#ffffff']);
});

test('shoots default scaled confetti', async t => {
  const page = t.context.page = await fixturePage();

  t.context.buffer = await confettiImage(page, {
    colors: ['#0000ff'],
    shapes: ['circle'],
    particleCount: 1,
    startVelocity: 0,
    gravity: 0,
    flat: true
  });
  t.context.image = await removeOpacity(t.context.buffer);

  const pixels = await totalPixels(t.context.image);

  const expected = 124;
  t.true(pixels > expected * .99 && pixels < expected * 1.01, `${pixels}±1% ≠ ${expected}`);
});

test('shoots larger scaled confetti', async t => {
  const page = t.context.page = await fixturePage();

  t.context.buffer = await confettiImage(page, {
    colors: ['#0000ff'],
    shapes: ['circle'],
    scalar: 10,
    particleCount: 1,
    startVelocity: 0,
    gravity: 0,
    flat: true
  });
  t.context.image = await removeOpacity(t.context.buffer);

  const pixels = await totalPixels(t.context.image);

  const expected = 11476;
  t.true(pixels > expected * .99 && pixels < expected * 1.01, `${pixels} ± 1% ≠ ${expected}`);
});

test('shoots confetti to the left', async t => {
  const page = t.context.page = await fixturePage();

  t.context.buffer = await confettiImage(page, {
    colors: ['#0000ff'],
    particleCount: 100,
    angle: 180,
    startVelocity: 20
  });
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColorsBySide(t.context.image);

  // left side has stuff on it
  t.deepEqual(pixels.left, ['#0000ff', '#ffffff']);
  // right side is all white
  t.deepEqual(pixels.right, ['#ffffff']);
});

test('shoots confetti to the right', async t => {
  const page = t.context.page = await fixturePage();

  t.context.buffer = await confettiImage(page, {
    colors: ['#0000ff'],
    particleCount: 100,
    angle: 0,
    startVelocity: 20
  });
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColorsBySide(t.context.image);

  // right side has stuff on it
  t.deepEqual(pixels.right, ['#0000ff', '#ffffff']);
  // left side is all white
  t.deepEqual(pixels.left, ['#ffffff']);
});

test('shoots flat confetti', async t => {
  const page = t.context.page = await fixturePage();

  // these parameters should create an image
  // that is the same every time
  t.context.buffer = await confettiImage(page, {
    startVelocity: 0,
    gravity: 0,
    scalar: 20,
    flat: 1,
    shapes: ['circle'],
    colors: ['ff0000']
  });
  t.context.image = await readImage(t.context.buffer);

  t.is(t.context.image.hash(), '8E0802208w0');
});

/*
 * Operational tests
 */

test('shoots confetti repeatedly using requestAnimationFrame', async t => {
  const page = t.context.page = await fixturePage();
  const time = 6 * 1000;

  let opts = {
    colors: ['#0000ff'],
    origin: { y: 1 },
    count: 1
  };

  // continuously animate more and more confetti
  // for 10 seconds... that should be longer than
  // this test... we won't wait for it anyway
  page.evaluate(`
    var opts = ${JSON.stringify(opts)};
    var end = Date.now() + (${time});

    (function frame() {
      confetti(opts);

      if (Date.now() < end) {
        requestAnimationFrame(frame);
      }
    }());
  `);

  await sleep(time / 4);
  const buff1 = await page.screenshot({ type: 'png' });
  await sleep(time / 4);
  const buff2 = await page.screenshot({ type: 'png' });
  await sleep(time / 4);
  const buff3 = await page.screenshot({ type: 'png' });
  await sleep(time / 4);
  const buff4 = await page.screenshot({ type: 'png' });

  const img1 = await readImage(buff1);
  const img2 = await readImage(buff2);
  const img3 = await readImage(buff3);
  const img4 = await readImage(buff4);
  const { width, height } = img1.bitmap;

  const comp = await emptyImg(width * 4, height);
  await comp.composite(img1, 0, 0);
  await comp.composite(img2, width, 0);
  await comp.composite(img3, width * 2, 0);
  await comp.composite(img4, width * 3, 0);

  t.context.buffer = await getImageBuffer(comp);
  t.context.image = await reduceImg(t.context.buffer);

  t.deepEqual(await uniqueColors(await reduceImg(img1)), ['#0000ff', '#ffffff']);
  t.deepEqual(await uniqueColors(await reduceImg(img2)), ['#0000ff', '#ffffff']);
  t.deepEqual(await uniqueColors(await reduceImg(img3)), ['#0000ff', '#ffffff']);
  t.deepEqual(await uniqueColors(await reduceImg(img4)), ['#0000ff', '#ffffff']);
});

test('uses promises when available', async t => {
  const page = t.context.page = await fixturePage();

  await page.evaluate(confetti({}, true));

  t.context.buffer = await page.screenshot({ type: 'png' });
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColors(t.context.image);

  // make sure that all confetti have disappeared
  t.deepEqual(pixels, ['#ffffff']);
});

test('removes the canvas when done', async t => {
  const page = t.context.page = await fixturePage();

  function hasCanvas() {
    return page.evaluate(`!!document.querySelector('canvas')`);
  }

  // make sure there is no canvas before executing confetti
  t.is(await hasCanvas(), false);

  const promise = page.evaluate(confetti({}, true));

  // confetti is running, make sure a canvas exists
  t.is(await hasCanvas(), true);

  await promise;

  // confetti is done, canvas should be gone now
  t.is(await hasCanvas(), false);
});

test('handles window resizes', async t => {
  const time = 50;

  const page = t.context.page = await fixturePage();
  await page.setViewport({ width: width / 2, height });

  let opts = {
    colors: ['#0000ff'],
    origin: { x: 1, y: 0 },
    angle: 0,
    startVelocity: 0,
    particleCount: 2
  };

  // continuously animate more and more confetti
  // for 10 seconds... that should be longer than
  // this test... we won't wait for it anyway
  page.evaluate(`
    var opts = ${JSON.stringify(opts)};
    var end = Date.now() + (10 * 1000);

    var promise = confetti(opts);

    var interval = setInterval(function() {
        if (Date.now() > end) {
            return clearInterval(interval);
        }

        confetti(opts);
    }, ${time});
  `);

  await sleep(time * 4);
  await page.setViewport({ width, height });
  await sleep(time * 4);

  t.context.buffer = await page.screenshot({ type: 'png' });
  t.context.image = await reduceImg(t.context.buffer);

  // chop this image into thirds
  let widthThird = Math.floor(width / 3);
  let first = t.context.image.clone().crop(widthThird * 0, 0, widthThird, height);
  let second = t.context.image.clone().crop(widthThird * 1, 0, widthThird, height);
  let third = t.context.image.clone().crop(widthThird * 2, 0, widthThird, height);

  // the first will be white, the second and third will have confetti in them
  t.deepEqual(await uniqueColors(first), ['#ffffff']);
  t.deepEqual(await uniqueColors(second), ['#0000ff', '#ffffff']);
  t.deepEqual(await uniqueColors(third), ['#0000ff', '#ffffff']);
});

test('stops and removes canvas immediately when `reset` is called', async t => {
  const page = t.context.page = await fixturePage();

  const promise = page.evaluate(`new Promise((resolve, reject) => {
    const results = [];
    results.push(!!document.querySelector('canvas'));
    confetti().then(() => {
      results.push('done');
    });
    results.push(!!document.querySelector('canvas'));
    confetti.reset();
    results.push(!!document.querySelector('canvas'));
    resolve(results);
  })`);

  const results = await promise;

  t.deepEqual(results, [false, true, false, 'done']);
});

/*
 * Shape from path
 */
test('[paths] `shapeFromPath` creates an object with a path and transform matrix', async t => {
  const page = t.context.page = await fixturePage();

  const result = await page.evaluate(`
    confetti.shapeFromPath('M0 0 L10 0 L10 10 L0 10z');
  `);

  t.deepEqual(result, {
    type: 'path',
    path: 'M0 0 L10 0 L10 10 L0 10z',
    matrix: [ 1, 0, 0, 1, -5, -5 ]
  });
});

test('[paths] `shapeFromPath` crops the shape and centers in the middle of the actual path object', async t => {
  const page = t.context.page = await fixturePage();

  const result = await page.evaluate(`
    confetti.shapeFromPath('M100 100 L110 100 L110 110 L100 110z');
  `);

  t.deepEqual(result, {
    type: 'path',
    path: 'M100 100 L110 100 L110 110 L100 110z',
    matrix: [ 1, 0, 0, 1, -105, -105 ]
  });
});

test('[paths] shoots confetti of a custom shape', async t => {
  const page = t.context.page = await fixturePage();

  const shape = await page.evaluate(`
    confetti.shapeFromPath('M0 10 L5 0 L10 10z');
  `);

  // these parameters should create an image
  // that is the same every time
  t.context.buffer = await confettiImage(page, {
    startVelocity: 0,
    gravity: 0,
    scalar: 20,
    flat: 1,
    shapes: [shape],
    colors: ['ff0000']
  });
  t.context.image = await readImage(t.context.buffer);

  t.is(t.context.image.hash(), '9I0p03d03c0');
});

/*
 * Shape from text
 */

const loadFont = async page => {
  // Noto Color Emoji
  const url = 'https://fonts.gstatic.com/s/notocoloremoji/v25/Yq6P-KqIXTD0t4D9z1ESnKM3-HpFabsE4tq3luCC7p-aXxcn.9.woff2';
  const name = 'Web Font';

  await page.evaluate(`
    Promise.resolve().then(async () => {
      const fontFile = new FontFace(
        "${name}",
        "url(${url})",
      );

      document.fonts.add(fontFile);

      await fontFile.load();
    });
  `, );

  return name;
};

const shapeFromTextImage = async (page, args) => {
  const { base64png, ...shape } = await page.evaluate(`
    Promise.resolve().then(async () => {
      const { bitmap, ...shape } = confetti.shapeFromText(${JSON.stringify(args)});

      const canvas = document.createElement('canvas');
      canvas.width = bitmap.width;
      canvas.height = bitmap.height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height);

      return {
        ...shape,
        base64png: canvas.toDataURL('image/png')
      };
    });
  `);

  return {
    ...shape,
    buffer: base64ToBuffer(base64png)
  };
};

test('[text] shapeFromText renders an emoji', async t => {
  const page = t.context.page = await fixturePage();

  const fontFace = await loadFont(page);

  const { buffer, ...shape } = await shapeFromTextImage(page, { text: '😀', fontFamily: `"${fontFace}"`, scalar: 10 });

  t.context.buffer = buffer;
  t.context.image = await readImage(buffer);

  t.deepEqual({
    hash: t.context.image.hash(),
    ...shape
  }, {
    type: 'bitmap',
    matrix: [ 0.1, 0, 0, 0.1, -5.7, -5.550000000000001 ],
    hash: 'c4y5z8b83AC'
  });
});

test('[text] shapeFromText works with just a string parameter', async t => {
  const page = t.context.page = await fixturePage();

  const shape = await page.evaluate(`
    confetti.shapeFromText("🍍");
  `);

  t.deepEqual(Object.keys(shape).sort(), ['type', 'bitmap', 'matrix'].sort());
  // the actual contents will differ from OS to OS, so just validate
  // the shape has some expected properties
  t.is(shape.type, 'bitmap');
  t.is(Array.isArray(shape.matrix), true);
  t.is(shape.matrix.length, 6);
});

test('[text] shapeFromText renders black text by default', async t => {
  const page = t.context.page = await fixturePage();

  const { buffer } = await shapeFromTextImage(page, { text: 'pie', scalar: 3 });

  t.context.buffer = buffer;
  t.context.image = await reduceImg(buffer);

  t.deepEqual(await uniqueColors(t.context.image), ['#000000', '#ffffff']);
});

test('[text] shapeFromText can optionally render text in a requested color', async t => {
  const page = t.context.page = await fixturePage();

  const { buffer } = await shapeFromTextImage(page, { text: 'pie', color: '#00ff00', scalar: 3 });

  t.context.buffer = buffer;
  t.context.image = await reduceImg(buffer);

  t.deepEqual(await uniqueColors(t.context.image), ['#00ff00', '#ffffff']);
});

// this test renders a black canvas in a headless browser
// but works fine when it is not headless
// eslint-disable-next-line ava/no-skip-test
test('[text] shoots confetti of an emoji shape', async t => {
  const page = t.context.page = await fixturePage();

  const fontFace = await loadFont(page);
  await page.evaluate(`window.__fontFamily = '"${fontFace}"'`);

  // these parameters should create an image
  // that is the same every time
  t.context.buffer = await confettiImage(page, {
    startVelocity: 0,
    gravity: 0,
    scalar: 10,
    flat: 1,
    ticks: 1000,
    // eslint-disable-next-line no-undef
    shapes: [() => confetti.shapeFromText({ text: '😀', fontFamily: __fontFamily, scalar: 10 })]
  });
  t.context.image = await readImage(t.context.buffer);

  t.is(t.context.image.hash(), 'cPpcSrcCjdC');
});

/*
 * Custom canvas
 */

const injectCanvas = async (page, opts = {}, createName = 'confetti.create') => {
  const allowResize = 'allowResize' in opts ? opts.allowResize : true;
  const useWorker = 'useWorker' in opts ? opts.useWorker : false;

  await page.evaluate(`
    var canvas = document.createElement('canvas');
    canvas.style.width = '100%';
    canvas.style.height = '100%';

    document.body.appendChild(canvas);

    window.myConfetti = ${createName}(canvas, {
      resize: ${!!allowResize},
      useWorker: ${!!useWorker}
    });
  `);
};

const getCanvasSize = async (page) => {
  return await page.evaluate(`
    var canvas = document.querySelector('canvas');
    var size = { width: canvas.width, height: canvas.height };
    Promise.resolve(size);
  `);
};

test('[custom canvas] can create instances of confetti in separate canvas', async t => {
  const page = t.context.page = await fixturePage();
  await injectCanvas(page);

  const beforeSize = await getCanvasSize(page);

  t.context.buffer = await confettiImage(page, {
    colors: ['#ff0000']
  }, 'myConfetti');
  t.context.image = await reduceImg(t.context.buffer);

  const afterSize = await getCanvasSize(page);

  t.deepEqual(await uniqueColors(t.context.image), ['#ff0000', '#ffffff']);
  t.notDeepEqual(beforeSize, afterSize);
});

test('[custom canvas] can use a custom canvas without resizing', async t => {
  const page = t.context.page = await fixturePage();
  await injectCanvas(page, { allowResize: false });

  const beforeSize = await getCanvasSize(page);

  t.context.buffer = await confettiImage(page, {
    colors: ['#ff0000'],
    startVelocity: 2,
    spread: 360,
    origin: { y: 0 }
  }, 'myConfetti');
  t.context.image = await reduceImg(t.context.buffer);

  const afterSize = await getCanvasSize(page);

  t.deepEqual(await uniqueColors(t.context.image), ['#ff0000', '#ffffff']);
  t.deepEqual(beforeSize, afterSize);
});

const resizeTest = async (t, createOpts, createName = 'confetti.create') => {
  const time = 50;

  const page = t.context.page = await fixturePage();
  await page.setViewport({ width: width / 2, height });

  let fireOpts = {
    colors: ['#0000ff'],
    origin: { x: 1, y: 0 },
    angle: 0,
    startVelocity: 0,
    particleCount: 2
  };

  // continuously animate more and more confetti
  // for 10 seconds... that should be longer than
  // this test... we won't wait for it anyway
  page.evaluate(`
    var canvas = document.createElement('canvas');
    canvas.style.width = '100%';
    canvas.style.height = '100%';

    document.body.appendChild(canvas);

    var myConfetti = ${createName}(canvas, ${JSON.stringify(createOpts)});

    var opts = ${JSON.stringify(fireOpts)};
    var end = Date.now() + (10 * 1000);

    var promise = myConfetti(opts);

    var interval = setInterval(function() {
      if (Date.now() > end) {
        return clearInterval(interval);
      }

      myConfetti(opts);
    }, ${time});
  `);

  await sleep(time * 4);
  await page.setViewport({ width, height });
  await sleep(time * 4);

  t.context.buffer = await page.screenshot({ type: 'png' });
  t.context.image = await reduceImg(t.context.buffer);

  // chop this image into thirds
  let widthThird = Math.floor(width / 3);
  let first = t.context.image.clone().crop(widthThird * 0, 0, widthThird, height);
  let second = t.context.image.clone().crop(widthThird * 1, 0, widthThird, height);
  let third = t.context.image.clone().crop(widthThird * 2, 0, widthThird, height);

  // the first will be white, the second and third will have confetti in them
  t.deepEqual(await uniqueColors(first), ['#ffffff']);
  t.deepEqual(await uniqueColors(second), ['#0000ff', '#ffffff']);
  t.deepEqual(await uniqueColors(third), ['#0000ff', '#ffffff']);
};

test('[custom canvas] resizes the custom canvas when the window resizes', async t => {
  await resizeTest(t, {
    resize: true
  });
});

test('[custom canvas] resizes the custom canvas when the window resizes and a worker is used', async t => {
  await resizeTest(t, {
    resize: true,
    useWorker: true
  });
});

test('[custom canvas] can use a custom canvas with workers and resize it', async t => {
  const page = t.context.page = await fixturePage();
  await injectCanvas(page, {
    allowResize: true,
    useWorker: true
  });

  const beforeSize = await getCanvasSize(page);

  t.context.buffer = await confettiImage(page, {
    colors: ['#ff0000']
  }, 'myConfetti');
  t.context.image = await reduceImg(t.context.buffer);

  const afterSize = await getCanvasSize(page);

  t.deepEqual(await uniqueColors(t.context.image), ['#ff0000', '#ffffff']);
  t.notDeepEqual(beforeSize, afterSize);
});

test('[custom canvas] shoots confetti repeatedly in defaut and custom canvas using requestAnimationFrame', async t => {
  const page = t.context.page = await fixturePage();
  await injectCanvas(page);
  const time = 6 * 1000;

  let regular = {
    colors: ['#0000ff'],
    origin: { x: 0.2, y: 1 },
    count: 1,
    spread: 10
  };
  let custom = {
    colors: ['#ff0000'],
    origin: { x: 0.8, y: 1 },
    count: 1,
    spread: 10
  };

  // continuously animate more and more confetti
  // for 10 seconds... that should be longer than
  // this test... we won't wait for it anyway
  page.evaluate(`
    var regular = ${JSON.stringify(regular)};
    var custom = ${JSON.stringify(custom)};
    var end = Date.now() + (${time});

    (function frame() {
      confetti(regular);
      myConfetti(custom);

      if (Date.now() < end) {
        requestAnimationFrame(frame);
      }
    }());
  `);

  await sleep(time / 4);
  const buff1 = await page.screenshot({ type: 'png' });
  await sleep(time / 4);
  const buff2 = await page.screenshot({ type: 'png' });
  await sleep(time / 4);
  const buff3 = await page.screenshot({ type: 'png' });
  await sleep(time / 4);
  const buff4 = await page.screenshot({ type: 'png' });

  const img1 = await readImage(buff1);
  const img2 = await readImage(buff2);
  const img3 = await readImage(buff3);
  const img4 = await readImage(buff4);
  const { width, height } = img1.bitmap;

  const comp = await emptyImg(width * 4, height);
  await comp.composite(img1, 0, 0);
  await comp.composite(img2, width, 0);
  await comp.composite(img3, width * 2, 0);
  await comp.composite(img4, width * 3, 0);

  t.context.buffer = await getImageBuffer(comp);
  t.context.image = await reduceImg(t.context.buffer);

  t.deepEqual(await uniqueColors(await reduceImg(img1)), ['#0000ff', '#ff0000', '#ffffff']);
  t.deepEqual(await uniqueColors(await reduceImg(img2)), ['#0000ff', '#ff0000', '#ffffff']);
  t.deepEqual(await uniqueColors(await reduceImg(img3)), ['#0000ff', '#ff0000', '#ffffff']);
  t.deepEqual(await uniqueColors(await reduceImg(img4)), ['#0000ff', '#ff0000', '#ffffff']);
});

test('[custom canvas] can initialize the same canvas multiple times when using a worker', async t => {
  const page = t.context.page = await fixturePage();
  await page.evaluate(`
    var canvas = document.createElement('canvas');
    canvas.id = 'testcanvas';
    canvas.style.width = '100%';
    canvas.style.height = '100%';

    document.body.appendChild(canvas);
  `);

  await page.evaluate(`
    var canvas = document.querySelector('#testcanvas');
    var instance1 = confetti.create(canvas, { resize: true, useWorker: true });
  `);

  t.context.buffer = await confettiImage(page, {
    colors: ['#ff0000'],
    startVelocity: 2,
    spread: 360,
  }, 'instance1');
  t.context.image = await reduceImg(t.context.buffer);

  t.deepEqual(await uniqueColors(t.context.image), ['#ff0000', '#ffffff']);

  await page.evaluate(`
    var canvas = document.querySelector('#testcanvas');
    var instance2 = confetti.create(canvas, { resize: true, useWorker: true });
  `);

  t.context.buffer = await confettiImage(page, {
    colors: ['#ff00ff'],
    startVelocity: 2,
    spread: 360,
  }, 'instance2');
  t.context.image = await reduceImg(t.context.buffer);

  // note: canvas is owned by the worker, so an existing animation will continue
  t.deepEqual(await uniqueColors(t.context.image), ['#ff0000', '#ff00ff', '#ffffff']);
});

test('[custom canvas] can initialize the same canvas multiple times without using a worker', async t => {
  const page = t.context.page = await fixturePage();
  await page.evaluate(`
    var canvas = document.createElement('canvas');
    canvas.id = 'testcanvas';
    canvas.style.width = '100%';
    canvas.style.height = '100%';

    document.body.appendChild(canvas);
  `);

  await page.evaluate(`
    var canvas = document.querySelector('#testcanvas');
    var instance1 = confetti.create(canvas, { resize: true, useWorker: false });
  `);

  t.context.buffer = await confettiImage(page, {
    colors: ['#ff0000'],
    startVelocity: 2,
    spread: 360,
  }, 'instance1');
  t.context.image = await reduceImg(t.context.buffer);

  t.deepEqual(await uniqueColors(t.context.image), ['#ff0000', '#ffffff']);

  await page.evaluate(`
    var canvas = document.querySelector('#testcanvas');
    var instance2 = confetti.create(canvas, { resize: true, useWorker: false });
  `);

  t.context.buffer = await confettiImage(page, {
    colors: ['#ff00ff'],
    startVelocity: 2,
    spread: 360,
  }, 'instance2');
  t.context.image = await reduceImg(t.context.buffer);

  // note: canvas can only be owned by one instance in the main thread,
  // so the animation is reset
  t.deepEqual(await uniqueColors(t.context.image), ['#ff00ff', '#ffffff']);
});

test('[custom canvas] calling `reset` method clears all existing confetti but more can be launched after', async t => {
  const page = t.context.page = await fixturePage();
  await injectCanvas(page);

  const prom1 = page.evaluate(confetti({ colors: ['#ff0000'] }, true, 'myConfetti'));
  await sleep(50);
  const img1 = await page.screenshot({ type: 'png' });

  await Promise.all([
    prom1,
    page.evaluate(`myConfetti.reset();`)
  ]);
  const img2 = await page.screenshot({ type: 'png' });

  const prom2 = page.evaluate(confetti({ colors: ['#ff0000'] }, true, 'myConfetti'));
  await sleep(50);
  const img3 = await page.screenshot({ type: 'png' });

  await prom2;

  t.deepEqual(await uniqueColors(await reduceImg(img1)), ['#ff0000', '#ffffff']);
  t.deepEqual(await uniqueColors(await reduceImg(img2)), ['#ffffff']);
  t.deepEqual(await uniqueColors(await reduceImg(img3)), ['#ff0000', '#ffffff']);
});

/*
 * Browserify tests
 */

test('[browserify] works using the browserify bundle', async t => {
  const page = t.context.page = await fixturePage('fixtures/page.browserify.html');

  await page.evaluate(`void confetti({
    colors: ['#00ff00'],
    particleCount: 200,
    spread: 270
  })`);

  await sleep(100);

  t.context.buffer = await page.screenshot({ type: 'png' });
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColors(t.context.image);

  t.deepEqual(pixels, ['#00ff00', '#ffffff']);
});

/*
 * Minified tests
 * using minification close to that of jsDelivr
 */

test('[minified] works using the terser minified and compressed code', async t => {
  const page = t.context.page = await fixturePage('fixtures/page.minified.html');

  await page.evaluate(`void confetti({
    colors: ['#ff00ff'],
    particleCount: 200,
    spread: 270
  })`);

  await sleep(100);

  t.context.buffer = await page.screenshot({ type: 'png' });
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColors(t.context.image);

  t.deepEqual(pixels, ['#ff00ff', '#ffffff']);
});

/*
 * ESM tests
 */

test('[esm] the esm module exposed confetti as the default', async t => {
  const page = t.context.page = await fixturePage('fixtures/page.module.html');

  t.context.buffer = await confettiImage(page, {
    colors: ['#ff00ff']
  }, 'confettiAlias');

  t.context.buffer = await page.screenshot({ type: 'png' });
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColors(t.context.image);

  t.deepEqual(pixels, ['#ff00ff', '#ffffff']);
});

test('[esm] the esm module exposed confetti.create as create', async t => {
  const page = t.context.page = await fixturePage('fixtures/page.module.html');

  await injectCanvas(page, { allowResize: true }, 'createAlias');

  t.context.buffer = await confettiImage(page, {
    colors: ['#ff00ff']
  }, 'myConfetti');
  t.context.image = await reduceImg(t.context.buffer);

  const pixels = await uniqueColors(t.context.image);

  t.deepEqual(pixels, ['#ff00ff', '#ffffff']);
});

test('[esm] exposed confetti method has a `reset` property', async t => {
  const page = t.context.page = await fixturePage('fixtures/page.module.html');

  t.is(await page.evaluate(`typeof confettiAlias.reset`), 'function');
});

test('[esm] exposed confetti method has a `shapeFromPath` property', async t => {
  const page = t.context.page = await fixturePage('fixtures/page.module.html');

  t.is(await page.evaluate(`typeof confettiAlias.shapeFromPath`), 'function');
});

test('[esm] exposed confetti method has a `shapeFromText` property', async t => {
  const page = t.context.page = await fixturePage('fixtures/page.module.html');

  t.is(await page.evaluate(`typeof confettiAlias.shapeFromText`), 'function');
});


================================================
FILE: test/ssr.test.js
================================================
import vm from 'vm';
import path from 'path';
import fs from 'fs';
import { promisify } from 'util';

import test from 'ava';
import root from 'rootrequire';

import pkg from '../package.json';

test('can be evaluated in a node vm', async t => {
  const file = await promisify(fs.readFile)(path.resolve(root, pkg.main), 'utf8');
  t.is(typeof file, 'string');

  const context = vm.createContext({ module: {} });
  vm.runInContext(file, context);

  t.is(typeof context.module.exports, 'function');
  t.is(typeof context.module.exports.create, 'function');
  t.is(typeof context.module.exports.reset, 'function');
});
Download .txt
gitextract_25sgzoeb/

├── .brackets.json
├── .editorconfig
├── .eslintrc.yml
├── .gitattributes
├── .github/
│   ├── funding.yml
│   └── workflows/
│       └── ci.yml
├── .gitignore
├── .npmignore
├── .npmrc
├── LICENSE
├── README.md
├── bin/
│   └── on_failure.sh
├── build/
│   ├── .eslintrc.yml
│   ├── build.js
│   └── serve.js
├── fixtures/
│   ├── debug.html
│   ├── page.browserify.html
│   ├── page.html
│   ├── page.minified.html
│   └── page.module.html
├── index.html
├── package.json
├── src/
│   └── confetti.js
└── test/
    ├── .eslintrc.yml
    ├── index.test.js
    └── ssr.test.js
Download .txt
SYMBOL INDEX (36 symbols across 4 files)

FILE: build/build.js
  function mkdir (line 8) | function mkdir(dir) {
  function readFile (line 20) | function readFile(file, encoding) {
  function writeFile (line 24) | function writeFile(file, content) {
  function buildCommonJs (line 28) | function buildCommonJs(content) {
  function buildModule (line 40) | function buildModule(content) {

FILE: build/serve.js
  constant PORT (line 7) | const PORT = 9001;

FILE: src/confetti.js
  function noop (line 35) | function noop() {}
  function promise (line 39) | function promise(func) {
  function decorate (line 127) | function decorate(worker) {
  function convert (line 251) | function convert(val, transform) {
  function isOk (line 255) | function isOk(val) {
  function prop (line 259) | function prop(options, name, transform) {
  function onlyPositiveInt (line 266) | function onlyPositiveInt(number){
  function randomInt (line 270) | function randomInt(min, max) {
  function toDecimal (line 275) | function toDecimal(str) {
  function colorsToRgb (line 279) | function colorsToRgb(colors) {
  function hexToRgb (line 283) | function hexToRgb(str) {
  function getOrigin (line 297) | function getOrigin(options) {
  function setCanvasWindowSize (line 305) | function setCanvasWindowSize(canvas) {
  function setCanvasRectSize (line 310) | function setCanvasRectSize(canvas) {
  function getCanvas (line 316) | function getCanvas(zIndex) {
  function ellipse (line 328) | function ellipse(context, x, y, radiusX, radiusY, rotation, startAngle, ...
  function randomPhysics (line 337) | function randomPhysics(opts) {
  function updateFetti (line 367) | function updateFetti(context, fetti) {
  function animate (line 480) | function animate(canvas, fettis, resizer, size, done) {
  function confettiCannon (line 546) | function confettiCannon(canvas, globalOpts) {
  function getDefaultFire (line 720) | function getDefaultFire() {
  function transformPath2D (line 727) | function transformPath2D(pathString, pathMatrix, x, y, scaleX, scaleY, r...
  function shapeFromPath (line 747) | function shapeFromPath(pathData) {
  function shapeFromText (line 807) | function shapeFromText(textData) {

FILE: test/index.test.js
  constant PORT (line 12) | const PORT = 9999;
  function serializeConfettiOptions (line 110) | function serializeConfettiOptions(opts) {
  function confetti (line 133) | function confetti(opts, wait = false, funcName = 'confetti') {
  function confettiImage (line 144) | async function confettiImage(page, opts = {}, funcName = 'confetti') {
  function hex (line 159) | function hex(n) {
  function hasCanvas (line 546) | function hasCanvas() {
Condensed preview — 26 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (130K chars).
[
  {
    "path": ".brackets.json",
    "chars": 420,
    "preview": "{\n    \"spaceUnits\": 2,\n    \"useTabChar\": false,\n    \"language\": {\n        \"javascript\": {\n            \"linting.prefer\": "
  },
  {
    "path": ".editorconfig",
    "chars": 187,
    "preview": "root = true\n\n[*]\nindent_style = space\nindent_size = 2\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ni"
  },
  {
    "path": ".eslintrc.yml",
    "chars": 112,
    "preview": "extends:\n  - eslint:recommended\nenv:\n  es6: false\n  browser: true\n  node: true\nrules:\n  semi: [ error, always ]\n"
  },
  {
    "path": ".gitattributes",
    "chars": 672,
    "preview": "# Auto detect text files and perform LF normalization\n* text=auto\n\n*.js     text eol=lf\n*.jsx    text eol=lf\n*.json   te"
  },
  {
    "path": ".github/funding.yml",
    "chars": 93,
    "preview": "github: catdad\ncustom: [\"https://www.paypal.me/kirilvatev\", \"https://venmo.com/Kiril-Vatev\"]\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 707,
    "preview": "name: CI\n\non:\n  push:\n  pull_request:\n    branches: [master]\n\npermissions:\n  id-token: write\n  contents: read\n\nenv:\n  FO"
  },
  {
    "path": ".gitignore",
    "chars": 561,
    "preview": "# Windows image file caches\nThumbs.db\nehthumbs.db\nDesktop.ini\n\n# Recycle Bin used on file shares\n$RECYCLE.BIN/\n\n# Window"
  },
  {
    "path": ".npmignore",
    "chars": 633,
    "preview": "# Windows image file caches\nThumbs.db\nehthumbs.db\nDesktop.ini\n\n# Recycle Bin used on file shares\n$RECYCLE.BIN/\n\n# Window"
  },
  {
    "path": ".npmrc",
    "chars": 19,
    "preview": "package-lock=false\n"
  },
  {
    "path": "LICENSE",
    "chars": 743,
    "preview": "ISC License\n\nCopyright (c) 2020, Kiril Vatev\n\nPermission to use, copy, modify, and/or distribute this software for any\np"
  },
  {
    "path": "README.md",
    "chars": 15390,
    "preview": "# [![Canvas Confetti](https://cdn.jsdelivr.net/gh/catdad-experiments/catdad-experiments-org@5ed78b/canvas-confetti/logo."
  },
  {
    "path": "bin/on_failure.sh",
    "chars": 505,
    "preview": "green=`tput setaf 2`\nreset=`tput sgr0`\n\nline_break () {\n  echo --------------------------------------\n}\n\nprint_green () "
  },
  {
    "path": "build/.eslintrc.yml",
    "chars": 93,
    "preview": "env:\n  es6: true\n  node: true\n  browser: false\nparser: babel-eslint\nrules:\n  no-console: off\n"
  },
  {
    "path": "build/build.js",
    "chars": 1329,
    "preview": "const fs = require('fs');\nconst { promisify } = require('util');\n\nconst { name, version, main } = require('../package.js"
  },
  {
    "path": "build/serve.js",
    "chars": 2079,
    "preview": "const path = require('path');\nconst http = require('http');\nconst send = require('send');\nconst root = require('rootrequ"
  },
  {
    "path": "fixtures/debug.html",
    "chars": 6701,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, in"
  },
  {
    "path": "fixtures/page.browserify.html",
    "chars": 280,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <title>test harness</title>\n</head>\n<body>\n  <script "
  },
  {
    "path": "fixtures/page.html",
    "chars": 297,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <title>test harness</title>\n\n  <style>\n    html, body"
  },
  {
    "path": "fixtures/page.minified.html",
    "chars": 277,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <title>test harness</title>\n</head>\n<body>\n  <script "
  },
  {
    "path": "fixtures/page.module.html",
    "chars": 473,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <title>test harness</title>\n\n  <style>\n    html, body"
  },
  {
    "path": "index.html",
    "chars": 30535,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, in"
  },
  {
    "path": "package.json",
    "chars": 1655,
    "preview": "{\n  \"name\": \"canvas-confetti\",\n  \"version\": \"1.9.4\",\n  \"description\": \"performant confetti animation in the browser\",\n  "
  },
  {
    "path": "src/confetti.js",
    "chars": 24727,
    "preview": "/* globals Map */\n\n(function main(global, module, isWorker, workerSize) {\n  var canUseWorker = !!(\n    global.Worker &&\n"
  },
  {
    "path": "test/.eslintrc.yml",
    "chars": 208,
    "preview": "extends:\n  - plugin:ava/recommended\nenv:\n  es6: true\n  node: true\n  browser: false\nparser: babel-eslint\nparserOptions:\n "
  },
  {
    "path": "test/index.test.js",
    "chars": 35087,
    "preview": "import fs from 'fs';\nimport http from 'http';\nimport path from 'path';\nimport { promisify } from 'util';\n\nimport test fr"
  },
  {
    "path": "test/ssr.test.js",
    "chars": 618,
    "preview": "import vm from 'vm';\nimport path from 'path';\nimport fs from 'fs';\nimport { promisify } from 'util';\n\nimport test from '"
  }
]

About this extraction

This page contains the full source code of the catdad/canvas-confetti GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 26 files (121.5 KB), approximately 34.6k tokens, and a symbol index with 36 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!