npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

jigsawpuzzlegame

v1.0.16

Published

A class for creating a jigsaw puzzle

Readme

JigsawPuzzle

A lightweight, reusable JavaScript class for creating interactive jigsaw puzzle games in web applications. Features customizable piece shapes, rotation support, save/load functionality, and touch/mouse controls.

Demo

Try it out live: https://jigsawpuzzleclass.raketten.net/game.html

Installation

npm i jigsawpuzzlegame

Quick Start

import { JigsawPuzzle } from 'jigsaw-puzzle';

const puzzle = new JigsawPuzzle('puzzle-container', {
    image: 'https://example.com/image.jpg',
    numPieces: 20,
    shapeType: 0,
    allowRotation: false,
    onReady: () => {
        puzzle.start();
    },
    onWin: () => {
        console.log('Puzzle solved!');
    }
});

HTML Setup

<div id="puzzle-container"></div>
<script type="module" src="your-script.js"></script>

Make sure your container has a defined size:

#puzzle-container {
    width: 100vw;
    height: 100vh;
    position: relative;
}

Configuration Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | image | string | null | URL or data URL of the image to use for the puzzle (ignored if savedData is provided) | | savedData | string|null | null | JSON string of saved game state:• Non-empty string: use this saved data• Empty string (""): load from localStorage• Not provided or null: use normal initialization with image and other parameters | | numPieces | number | 20 | Number of puzzle pieces (approximate - actual count depends on optimal grid layout, ignored if savedData is provided) | | shapeType | number | 0 | Shape type for puzzle pieces (0-3, ignored if savedData is provided):0 - Classic jigsaw shape (curved tabs)1 - Alternative shape 12 - Alternative shape 23 - Straight edges (rectangular pieces) | | allowRotation | boolean | false | Whether pieces can be rotated by clicking/tapping (90° increments, ignored if savedData is provided) | | onReady | function | null | Callback function called when the puzzle is ready (image loaded and displayed) | | onWin | function | null | Callback function called when the puzzle is completed | | onStart | function | null | Callback function called when a game starts | | onStop | function | null | Callback function called when a game is stopped | | onMerged | function | null | Callback function called when puzzle pieces are merged together (receives the merged piece as parameter) | | onChanged | function | null | Callback function called when a piece is moved or changed (receives the piece as parameter) | | onDeleted | function | null | Callback function called when a piece is deleted/merged into another piece (receives the deleted piece as parameter) |

API Methods

start()

Starts a new game with the current settings. Creates the puzzle pieces and distributes them.

puzzle.start();

Important: Call this only after the puzzle is ready (use the onReady callback).

stop()

Stops the current game and returns to the image preview state.

puzzle.stop();

reset()

Resets the puzzle to initial state. Reloads the current image and prepares for a new game.

puzzle.reset();
// Then wait for onReady callback and call puzzle.start()

setImage(imageUrl)

Sets a new image for the puzzle.

Parameters:

  • imageUrl (string) - URL or data URL of the image
puzzle.setImage('https://example.com/new-image.jpg');
// Image will reload, wait for onReady callback

setOptions(newOptions)

Updates puzzle options without creating a new instance.

Parameters:

  • newOptions (object) - Object with options to update (partial updates allowed)
puzzle.setOptions({
    numPieces: 50,
    allowRotation: true,
    shapeType: 1
});

save([callback])

Saves the current game state. Gets the state data, converts it to a JSON string, then either calls the callback with the string or saves to localStorage.

Parameters:

  • callback (function, optional) - Function that receives the saved data as JSON string. If not provided, saves to localStorage automatically.
// Save to localStorage (default)
puzzle.save();

// Save with custom callback
puzzle.save((savedData) => {
    localStorage.setItem('myPuzzleSave', savedData);
    // Or send to server, download as file, etc.
});

Loading Saved Games

To load a saved game, create a new puzzle instance with the savedData option:

// Load from explicit string
const savedString = localStorage.getItem('myPuzzleSave');
const puzzle = new JigsawPuzzle('puzzle-container', {
    savedData: savedString,
    onReady: () => puzzle.start()
});

// Load from localStorage automatically (pass empty string)
const puzzle = new JigsawPuzzle('puzzle-container', {
    savedData: "",  // Empty string triggers localStorage lookup
    onReady: () => puzzle.start()
});

// Create new puzzle (no saved data)
const puzzle = new JigsawPuzzle('puzzle-container', {
    image: 'image.jpg',
    numPieces: 25,
    onReady: () => puzzle.start()
});

destroy()

Completely destroys the puzzle instance, cleaning up all resources. Use this when you want to remove the puzzle and create a new one in the same container.

puzzle.destroy();
puzzle = new JigsawPuzzle('puzzle-container', {
    image: 'new-image.jpg',
    numPieces: 30
});

Complete Example

import { JigsawPuzzle } from 'jigsaw-puzzle';

const puzzle = new JigsawPuzzle('puzzle-container', {
    image: 'https://example.com/image.jpg',
    numPieces: 20,
    shapeType: 0,
    allowRotation: false,
    onReady: () => {
        // Puzzle is ready, start the game
        puzzle.start();
    },
    onWin: () => {
        alert('Congratulations! You solved the puzzle!');
    },
    onStart: () => {
        console.log('Game started');
    },
    onStop: () => {
        console.log('Game stopped');
    },
    onMerged: (piece) => {
        console.log('Pieces merged!', piece);
    },
    onChanged: (piece) => {
        console.log('Piece moved', piece);
    },
    onDeleted: (piece) => {
        console.log('Piece deleted', piece);
    }
});

// Save game
function saveGame() {
    puzzle.save((data) => {
        localStorage.setItem('puzzleSave', data);
        console.log('Game saved!');
    });
}

// Load game - create new instance with saved data
function loadGame() {
    const saved = localStorage.getItem('puzzleSave');
    if (saved) {
        if (puzzle) puzzle.destroy();
        puzzle = new JigsawPuzzle('puzzle-container', {
            savedData: saved,
            onReady: () => puzzle.start(),
            onWin: () => {
                alert('You won!');
            }
        });
    }
}

User Interactions

  • Mouse/Touch: Click and drag pieces to move them
  • Rotation: If allowRotation is enabled, quick click/tap rotates pieces 90°
  • Piece Merging: When pieces are close and correctly aligned, they automatically merge
  • Pan: Click and drag on empty space to pan all pieces
  • Zoom: Mouse wheel to zoom in/out, or pinch gesture on touch devices

Browser Compatibility

Requires modern browser features:

  • ES6 Modules support
  • Canvas API
  • Path2D API
  • Touch events (for mobile support)

Works in all modern browsers (Chrome, Firefox, Safari, Edge).

Styling

The library automatically injects its required CSS styles when loaded, so no external CSS file is needed. The styles are injected once per page load, even if multiple puzzle instances are created.

The puzzle uses these CSS classes (automatically styled by the library):

  • .polypiece - Individual puzzle pieces
  • .polypiece.moving - Pieces during animation
  • .gameCanvas - Reference image canvas (hidden during play)

You can override these styles in your own CSS if needed. The library injects a <style> element with id jigsaw-puzzle-styles that you can target or override.

Troubleshooting

Puzzle doesn't start

  • Make sure you're calling start() in the onReady callback
  • Check that the image URL is valid and accessible (CORS issues if loading from different domain)
  • Verify the container element exists and has a size

Image doesn't load

  • Check browser console for CORS errors
  • Use data URLs or images from the same domain
  • Ensure the image URL is correct

Pieces don't merge

  • Make sure pieces are close enough (the puzzle calculates optimal distance)
  • Check that pieces are in the same rotation if rotation is enabled
  • Verify pieces are correctly aligned

License

Copyright (c) 2026 by Dillon (https://codepen.io/Dillo/pen/QWKLYab) & Henrik Rasmussen (https://www.raketten.net)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Authors

  • Dillon - https://codepen.io/Dillo/pen/QWKLYab
  • Henrik Rasmussen - https://www.raketten.net