jigsawpuzzlegame 1.0.11 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,287 +1,299 @@
1
- # JigsawPuzzle
2
-
3
- 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.
4
-
5
- ## Demo
6
-
7
- Try it out live: [https://jigsawpuzzleclass.raketten.net/game.html](https://jigsawpuzzleclass.raketten.net/game.html)
8
-
9
- ## Installation
10
-
11
- ```bash
12
- npm i jigsawpuzzlegame
13
- ```
14
-
15
- ## Quick Start
16
-
17
- ```javascript
18
- import { JigsawPuzzle } from 'jigsaw-puzzle';
19
-
20
- const puzzle = new JigsawPuzzle('puzzle-container', {
21
- image: 'https://example.com/image.jpg',
22
- numPieces: 20,
23
- shapeType: 0,
24
- allowRotation: false,
25
- onReady: () => {
26
- puzzle.start();
27
- },
28
- onWin: () => {
29
- console.log('Puzzle solved!');
30
- }
31
- });
32
- ```
33
-
34
- ## HTML Setup
35
-
36
- ```html
37
- <div id="puzzle-container"></div>
38
- <script type="module" src="your-script.js"></script>
39
- ```
40
-
41
- Make sure your container has a defined size:
42
-
43
- ```css
44
- #puzzle-container {
45
- width: 100vw;
46
- height: 100vh;
47
- position: relative;
48
- }
49
- ```
50
-
51
- ## Configuration Options
52
-
53
- | Option | Type | Default | Description |
54
- |--------|------|---------|-------------|
55
- | `image` | string | `null` | URL or data URL of the image to use for the puzzle (ignored if `savedData` is provided) |
56
- | `savedData` | string\|null | `null` | JSON string of saved game state:<br>• Non-empty string: use this saved data<br>• Empty string (`""`): load from localStorage<br>• Not provided or `null`: use normal initialization with `image` and other parameters |
57
- | `numPieces` | number | `20` | Number of puzzle pieces (approximate - actual count depends on optimal grid layout, ignored if `savedData` is provided) |
58
- | `shapeType` | number | `0` | Shape type for puzzle pieces (0-3, ignored if `savedData` is provided):<br>• `0` - Classic jigsaw shape (curved tabs)<br>• `1` - Alternative shape 1<br>• `2` - Alternative shape 2<br>• `3` - Straight edges (rectangular pieces) |
59
- | `allowRotation` | boolean | `false` | Whether pieces can be rotated by clicking/tapping (90° increments, ignored if `savedData` is provided) |
60
- | `onReady` | function | `null` | Callback function called when the puzzle is ready (image loaded and displayed) |
61
- | `onWin` | function | `null` | Callback function called when the puzzle is completed |
62
- | `onStart` | function | `null` | Callback function called when a game starts |
63
- | `onStop` | function | `null` | Callback function called when a game is stopped |
64
-
65
- ## API Methods
66
-
67
- ### `start()`
68
-
69
- Starts a new game with the current settings. Creates the puzzle pieces and distributes them.
70
-
71
- ```javascript
72
- puzzle.start();
73
- ```
74
-
75
- **Important:** Call this only after the puzzle is ready (use the `onReady` callback).
76
-
77
- ### `stop()`
78
-
79
- Stops the current game and returns to the image preview state.
80
-
81
- ```javascript
82
- puzzle.stop();
83
- ```
84
-
85
- ### `reset()`
86
-
87
- Resets the puzzle to initial state. Reloads the current image and prepares for a new game.
88
-
89
- ```javascript
90
- puzzle.reset();
91
- // Then wait for onReady callback and call puzzle.start()
92
- ```
93
-
94
- ### `setImage(imageUrl)`
95
-
96
- Sets a new image for the puzzle.
97
-
98
- **Parameters:**
99
- - `imageUrl` (string) - URL or data URL of the image
100
-
101
- ```javascript
102
- puzzle.setImage('https://example.com/new-image.jpg');
103
- // Image will reload, wait for onReady callback
104
- ```
105
-
106
- ### `setOptions(newOptions)`
107
-
108
- Updates puzzle options without creating a new instance.
109
-
110
- **Parameters:**
111
- - `newOptions` (object) - Object with options to update (partial updates allowed)
112
-
113
- ```javascript
114
- puzzle.setOptions({
115
- numPieces: 50,
116
- allowRotation: true,
117
- shapeType: 1
118
- });
119
- ```
120
-
121
- ### `save([callback])`
122
-
123
- 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.
124
-
125
- **Parameters:**
126
- - `callback` (function, optional) - Function that receives the saved data as JSON string. If not provided, saves to localStorage automatically.
127
-
128
- ```javascript
129
- // Save to localStorage (default)
130
- puzzle.save();
131
-
132
- // Save with custom callback
133
- puzzle.save((savedData) => {
134
- localStorage.setItem('myPuzzleSave', savedData);
135
- // Or send to server, download as file, etc.
136
- });
137
- ```
138
-
139
- ### Loading Saved Games
140
-
141
- To load a saved game, create a new puzzle instance with the `savedData` option:
142
-
143
- ```javascript
144
- // Load from explicit string
145
- const savedString = localStorage.getItem('myPuzzleSave');
146
- const puzzle = new JigsawPuzzle('puzzle-container', {
147
- savedData: savedString,
148
- onReady: () => puzzle.start()
149
- });
150
-
151
- // Load from localStorage automatically (pass empty string)
152
- const puzzle = new JigsawPuzzle('puzzle-container', {
153
- savedData: "", // Empty string triggers localStorage lookup
154
- onReady: () => puzzle.start()
155
- });
156
-
157
- // Create new puzzle (no saved data)
158
- const puzzle = new JigsawPuzzle('puzzle-container', {
159
- image: 'image.jpg',
160
- numPieces: 25,
161
- onReady: () => puzzle.start()
162
- });
163
- ```
164
-
165
- ### `destroy()`
166
-
167
- 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.
168
-
169
- ```javascript
170
- puzzle.destroy();
171
- puzzle = new JigsawPuzzle('puzzle-container', {
172
- image: 'new-image.jpg',
173
- numPieces: 30
174
- });
175
- ```
176
-
177
- ## Complete Example
178
-
179
- ```javascript
180
- import { JigsawPuzzle } from 'jigsaw-puzzle';
181
-
182
- const puzzle = new JigsawPuzzle('puzzle-container', {
183
- image: 'https://example.com/image.jpg',
184
- numPieces: 20,
185
- shapeType: 0,
186
- allowRotation: false,
187
- onReady: () => {
188
- // Puzzle is ready, start the game
189
- puzzle.start();
190
- },
191
- onWin: () => {
192
- alert('Congratulations! You solved the puzzle!');
193
- },
194
- onStart: () => {
195
- console.log('Game started');
196
- },
197
- onStop: () => {
198
- console.log('Game stopped');
199
- }
200
- });
201
-
202
- // Save game
203
- function saveGame() {
204
- puzzle.save((data) => {
205
- localStorage.setItem('puzzleSave', data);
206
- console.log('Game saved!');
207
- });
208
- }
209
-
210
- // Load game - create new instance with saved data
211
- function loadGame() {
212
- const saved = localStorage.getItem('puzzleSave');
213
- if (saved) {
214
- if (puzzle) puzzle.destroy();
215
- puzzle = new JigsawPuzzle('puzzle-container', {
216
- savedData: saved,
217
- onReady: () => puzzle.start(),
218
- onWin: () => {
219
- alert('You won!');
220
- }
221
- });
222
- }
223
- }
224
- ```
225
-
226
- ## User Interactions
227
-
228
- - **Mouse/Touch:** Click and drag pieces to move them
229
- - **Rotation:** If `allowRotation` is enabled, quick click/tap rotates pieces 90°
230
- - **Piece Merging:** When pieces are close and correctly aligned, they automatically merge
231
- - **Pan:** Click and drag on empty space to pan all pieces
232
- - **Zoom:** Mouse wheel to zoom in/out, or pinch gesture on touch devices
233
-
234
- ## Browser Compatibility
235
-
236
- Requires modern browser features:
237
- - ES6 Modules support
238
- - Canvas API
239
- - Path2D API
240
- - Touch events (for mobile support)
241
-
242
- Works in all modern browsers (Chrome, Firefox, Safari, Edge).
243
-
244
- ## Styling
245
-
246
- 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.
247
-
248
- The puzzle uses these CSS classes (automatically styled by the library):
249
-
250
- - `.polypiece` - Individual puzzle pieces
251
- - `.polypiece.moving` - Pieces during animation
252
- - `.gameCanvas` - Reference image canvas (hidden during play)
253
-
254
- 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.
255
-
256
- ## Troubleshooting
257
-
258
- ### Puzzle doesn't start
259
- - Make sure you're calling `start()` in the `onReady` callback
260
- - Check that the image URL is valid and accessible (CORS issues if loading from different domain)
261
- - Verify the container element exists and has a size
262
-
263
- ### Image doesn't load
264
- - Check browser console for CORS errors
265
- - Use data URLs or images from the same domain
266
- - Ensure the image URL is correct
267
-
268
- ### Pieces don't merge
269
- - Make sure pieces are close enough (the puzzle calculates optimal distance)
270
- - Check that pieces are in the same rotation if rotation is enabled
271
- - Verify pieces are correctly aligned
272
-
273
- ## License
274
-
275
- Copyright (c) 2026 by Dillon (https://codepen.io/Dillo/pen/QWKLYab) & Henrik Rasmussen (https://www.raketten.net)
276
-
277
- 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:
278
-
279
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
280
-
281
- 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.
282
-
283
- ## Authors
284
-
285
- - Dillon - https://codepen.io/Dillo/pen/QWKLYab
286
- - Henrik Rasmussen - https://www.raketten.net
287
-
1
+ # JigsawPuzzle
2
+
3
+ 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.
4
+
5
+ ## Demo
6
+
7
+ Try it out live: [https://jigsawpuzzleclass.raketten.net/game.html](https://jigsawpuzzleclass.raketten.net/game.html)
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm i jigsawpuzzlegame
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```javascript
18
+ import { JigsawPuzzle } from 'jigsaw-puzzle';
19
+
20
+ const puzzle = new JigsawPuzzle('puzzle-container', {
21
+ image: 'https://example.com/image.jpg',
22
+ numPieces: 20,
23
+ shapeType: 0,
24
+ allowRotation: false,
25
+ onReady: () => {
26
+ puzzle.start();
27
+ },
28
+ onWin: () => {
29
+ console.log('Puzzle solved!');
30
+ }
31
+ });
32
+ ```
33
+
34
+ ## HTML Setup
35
+
36
+ ```html
37
+ <div id="puzzle-container"></div>
38
+ <script type="module" src="your-script.js"></script>
39
+ ```
40
+
41
+ Make sure your container has a defined size:
42
+
43
+ ```css
44
+ #puzzle-container {
45
+ width: 100vw;
46
+ height: 100vh;
47
+ position: relative;
48
+ }
49
+ ```
50
+
51
+ ## Configuration Options
52
+
53
+ | Option | Type | Default | Description |
54
+ |--------|------|---------|-------------|
55
+ | `image` | string | `null` | URL or data URL of the image to use for the puzzle (ignored if `savedData` is provided) |
56
+ | `savedData` | string\|null | `null` | JSON string of saved game state:<br>• Non-empty string: use this saved data<br>• Empty string (`""`): load from localStorage<br>• Not provided or `null`: use normal initialization with `image` and other parameters |
57
+ | `numPieces` | number | `20` | Number of puzzle pieces (approximate - actual count depends on optimal grid layout, ignored if `savedData` is provided) |
58
+ | `shapeType` | number | `0` | Shape type for puzzle pieces (0-3, ignored if `savedData` is provided):<br>• `0` - Classic jigsaw shape (curved tabs)<br>• `1` - Alternative shape 1<br>• `2` - Alternative shape 2<br>• `3` - Straight edges (rectangular pieces) |
59
+ | `allowRotation` | boolean | `false` | Whether pieces can be rotated by clicking/tapping (90° increments, ignored if `savedData` is provided) |
60
+ | `onReady` | function | `null` | Callback function called when the puzzle is ready (image loaded and displayed) |
61
+ | `onWin` | function | `null` | Callback function called when the puzzle is completed |
62
+ | `onStart` | function | `null` | Callback function called when a game starts |
63
+ | `onStop` | function | `null` | Callback function called when a game is stopped |
64
+ | `onMerged` | function | `null` | Callback function called when puzzle pieces are merged together (receives the merged piece as parameter) |
65
+ | `onChanged` | function | `null` | Callback function called when a piece is moved or changed (receives the piece as parameter) |
66
+ | `onDeleted` | function | `null` | Callback function called when a piece is deleted/merged into another piece (receives the deleted piece as parameter) |
67
+
68
+ ## API Methods
69
+
70
+ ### `start()`
71
+
72
+ Starts a new game with the current settings. Creates the puzzle pieces and distributes them.
73
+
74
+ ```javascript
75
+ puzzle.start();
76
+ ```
77
+
78
+ **Important:** Call this only after the puzzle is ready (use the `onReady` callback).
79
+
80
+ ### `stop()`
81
+
82
+ Stops the current game and returns to the image preview state.
83
+
84
+ ```javascript
85
+ puzzle.stop();
86
+ ```
87
+
88
+ ### `reset()`
89
+
90
+ Resets the puzzle to initial state. Reloads the current image and prepares for a new game.
91
+
92
+ ```javascript
93
+ puzzle.reset();
94
+ // Then wait for onReady callback and call puzzle.start()
95
+ ```
96
+
97
+ ### `setImage(imageUrl)`
98
+
99
+ Sets a new image for the puzzle.
100
+
101
+ **Parameters:**
102
+ - `imageUrl` (string) - URL or data URL of the image
103
+
104
+ ```javascript
105
+ puzzle.setImage('https://example.com/new-image.jpg');
106
+ // Image will reload, wait for onReady callback
107
+ ```
108
+
109
+ ### `setOptions(newOptions)`
110
+
111
+ Updates puzzle options without creating a new instance.
112
+
113
+ **Parameters:**
114
+ - `newOptions` (object) - Object with options to update (partial updates allowed)
115
+
116
+ ```javascript
117
+ puzzle.setOptions({
118
+ numPieces: 50,
119
+ allowRotation: true,
120
+ shapeType: 1
121
+ });
122
+ ```
123
+
124
+ ### `save([callback])`
125
+
126
+ 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.
127
+
128
+ **Parameters:**
129
+ - `callback` (function, optional) - Function that receives the saved data as JSON string. If not provided, saves to localStorage automatically.
130
+
131
+ ```javascript
132
+ // Save to localStorage (default)
133
+ puzzle.save();
134
+
135
+ // Save with custom callback
136
+ puzzle.save((savedData) => {
137
+ localStorage.setItem('myPuzzleSave', savedData);
138
+ // Or send to server, download as file, etc.
139
+ });
140
+ ```
141
+
142
+ ### Loading Saved Games
143
+
144
+ To load a saved game, create a new puzzle instance with the `savedData` option:
145
+
146
+ ```javascript
147
+ // Load from explicit string
148
+ const savedString = localStorage.getItem('myPuzzleSave');
149
+ const puzzle = new JigsawPuzzle('puzzle-container', {
150
+ savedData: savedString,
151
+ onReady: () => puzzle.start()
152
+ });
153
+
154
+ // Load from localStorage automatically (pass empty string)
155
+ const puzzle = new JigsawPuzzle('puzzle-container', {
156
+ savedData: "", // Empty string triggers localStorage lookup
157
+ onReady: () => puzzle.start()
158
+ });
159
+
160
+ // Create new puzzle (no saved data)
161
+ const puzzle = new JigsawPuzzle('puzzle-container', {
162
+ image: 'image.jpg',
163
+ numPieces: 25,
164
+ onReady: () => puzzle.start()
165
+ });
166
+ ```
167
+
168
+ ### `destroy()`
169
+
170
+ 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.
171
+
172
+ ```javascript
173
+ puzzle.destroy();
174
+ puzzle = new JigsawPuzzle('puzzle-container', {
175
+ image: 'new-image.jpg',
176
+ numPieces: 30
177
+ });
178
+ ```
179
+
180
+ ## Complete Example
181
+
182
+ ```javascript
183
+ import { JigsawPuzzle } from 'jigsaw-puzzle';
184
+
185
+ const puzzle = new JigsawPuzzle('puzzle-container', {
186
+ image: 'https://example.com/image.jpg',
187
+ numPieces: 20,
188
+ shapeType: 0,
189
+ allowRotation: false,
190
+ onReady: () => {
191
+ // Puzzle is ready, start the game
192
+ puzzle.start();
193
+ },
194
+ onWin: () => {
195
+ alert('Congratulations! You solved the puzzle!');
196
+ },
197
+ onStart: () => {
198
+ console.log('Game started');
199
+ },
200
+ onStop: () => {
201
+ console.log('Game stopped');
202
+ },
203
+ onMerged: (piece) => {
204
+ console.log('Pieces merged!', piece);
205
+ },
206
+ onChanged: (piece) => {
207
+ console.log('Piece moved', piece);
208
+ },
209
+ onDeleted: (piece) => {
210
+ console.log('Piece deleted', piece);
211
+ }
212
+ });
213
+
214
+ // Save game
215
+ function saveGame() {
216
+ puzzle.save((data) => {
217
+ localStorage.setItem('puzzleSave', data);
218
+ console.log('Game saved!');
219
+ });
220
+ }
221
+
222
+ // Load game - create new instance with saved data
223
+ function loadGame() {
224
+ const saved = localStorage.getItem('puzzleSave');
225
+ if (saved) {
226
+ if (puzzle) puzzle.destroy();
227
+ puzzle = new JigsawPuzzle('puzzle-container', {
228
+ savedData: saved,
229
+ onReady: () => puzzle.start(),
230
+ onWin: () => {
231
+ alert('You won!');
232
+ }
233
+ });
234
+ }
235
+ }
236
+ ```
237
+
238
+ ## User Interactions
239
+
240
+ - **Mouse/Touch:** Click and drag pieces to move them
241
+ - **Rotation:** If `allowRotation` is enabled, quick click/tap rotates pieces 90°
242
+ - **Piece Merging:** When pieces are close and correctly aligned, they automatically merge
243
+ - **Pan:** Click and drag on empty space to pan all pieces
244
+ - **Zoom:** Mouse wheel to zoom in/out, or pinch gesture on touch devices
245
+
246
+ ## Browser Compatibility
247
+
248
+ Requires modern browser features:
249
+ - ES6 Modules support
250
+ - Canvas API
251
+ - Path2D API
252
+ - Touch events (for mobile support)
253
+
254
+ Works in all modern browsers (Chrome, Firefox, Safari, Edge).
255
+
256
+ ## Styling
257
+
258
+ 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.
259
+
260
+ The puzzle uses these CSS classes (automatically styled by the library):
261
+
262
+ - `.polypiece` - Individual puzzle pieces
263
+ - `.polypiece.moving` - Pieces during animation
264
+ - `.gameCanvas` - Reference image canvas (hidden during play)
265
+
266
+ 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.
267
+
268
+ ## Troubleshooting
269
+
270
+ ### Puzzle doesn't start
271
+ - Make sure you're calling `start()` in the `onReady` callback
272
+ - Check that the image URL is valid and accessible (CORS issues if loading from different domain)
273
+ - Verify the container element exists and has a size
274
+
275
+ ### Image doesn't load
276
+ - Check browser console for CORS errors
277
+ - Use data URLs or images from the same domain
278
+ - Ensure the image URL is correct
279
+
280
+ ### Pieces don't merge
281
+ - Make sure pieces are close enough (the puzzle calculates optimal distance)
282
+ - Check that pieces are in the same rotation if rotation is enabled
283
+ - Verify pieces are correctly aligned
284
+
285
+ ## License
286
+
287
+ Copyright (c) 2026 by Dillon (https://codepen.io/Dillo/pen/QWKLYab) & Henrik Rasmussen (https://www.raketten.net)
288
+
289
+ 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:
290
+
291
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
292
+
293
+ 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.
294
+
295
+ ## Authors
296
+
297
+ - Dillon - https://codepen.io/Dillo/pen/QWKLYab
298
+ - Henrik Rasmussen - https://www.raketten.net
299
+