Skip to content

Commit

Permalink
Lot of breaking changes
Browse files Browse the repository at this point in the history
- renamed methods, properties and options
- added setMaxCachedImages
- added loadProgress property
  • Loading branch information
reindernijhoff committed May 14, 2024
1 parent 10ee3db commit 0373c79
Show file tree
Hide file tree
Showing 10 changed files with 230 additions and 89 deletions.
60 changes: 54 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ const options = {
// In that case, you will use the tar file to serve (super low res) preview images shown before the
// direct image loading completes.

wrap: true,
size: 'cover',
loop: true,
objectFit: 'cover',
};

const sequence = new FastImageSequence(containerElement, options);
Expand All @@ -55,6 +55,32 @@ In the case of a large image sequence, the normal usage of this library involves

By setting callbacks for URLs and loading the tar file yourself, you can set different functions for different devices and/or different supported image file formats. This allows you to optimize the image sequence for your specific project needs.

### Available options for FastImageSequence

- **frames**: `number` - Number of frames in the sequence. Required.
- **imageURLCallback**: `((index: number) => string) | undefined` - Callback returning the URL of an image given its index. Optional.
- **tarURL**: `string | undefined` - URL of the tar file containing images. Optional.
- **tarImageURLCallback**: `((index: number) => string) | undefined` - Callback returning the URL of an image in the tar file given its index. Optional.


- **loop**: `boolean` - Whether the sequence should loop. Default: `false`
- **maxConnectionLimit**: `number` - Maximum number of concurrent connections for fetching images. Default: `4`
- **maxCachedImages**: `number` - Number of images to cache. Default: `32`


- **objectFit**: `'contain' | 'cover'` - How the image should fit the canvas. Default: `'cover'`
- **horizontalAlign**: `number` - Horizontal alignment of the image. Default: `0.5`
- **verticalAlign**: `number` - Vertical alignment of the image. Default: `0.5`


- **fillStyle**: `string` - Fill style of the canvas. Default: `'#00000000'`
- **preloadAllTarImages**: `boolean` - Preload all images from the tar file. Default: `false`
- **useWorkerForTar**: `boolean` - Use a worker for handling the tar file. Default: `true`
- **useWorkerForImage**: `boolean` - Use a worker for fetching images. Default: `!isMobile()`
- **clearCanvas**: `boolean` - Clear the canvas before drawing. Default: `false`
- **showDebugInfo**: `boolean` - Show debug info. Default: `false`
- **name**: `string` - Name of the FastImageSequence instance. Default: `'FastImageSequence'`

## Methods

The following methods are available for a FastImageSequence object:
Expand Down Expand Up @@ -87,20 +113,20 @@ This method stops playing the image sequence.
sequence.stop();
```

### isPlaying
### playing

This getter method returns a boolean indicating whether the image sequence is playing.

```typescript
const playingStatus = sequence.isPlaying;
const playingStatus = sequence.playing;
```

### isPaused
### paused

This getter method returns a boolean indicating whether the image sequence is paused.

```typescript
const pausedStatus = sequence.isPaused;
const pausedStatus = sequence.paused;
```

### progress
Expand All @@ -117,6 +143,16 @@ sequence.progress = value;

- `value` is a number that sets the current progress of the image sequence.

### loadProgress

This is a getter method that retrieves the current load progress of the image sequence.

```typescript
const currentLoadProgress = sequence.loadProgress;
```

The `loadProgress` property returns a number between 0 and 1, representing the current load progress of the image sequence. Note that the value can decrease if the sequence is played and new frames are loaded.

### getFrameImage(index: number): Promise<HTMLImageElement | ImageBitmap>

This method gets the image of a specific frame and returns a Promise that resolves with the image of the frame.
Expand All @@ -127,6 +163,18 @@ sequence.getFrameImage(index);

- `index` is the index of the frame to get the image from.

### setMaxCachedImages(maxCache: number, onProgress?: (progress: number) => void): Promise<void>

This method sets the number of images that should be preloaded and cached in memory and returns a Promise that resolves when all these images are preloaded and cached.

```typescript
sequence.setNumberOfCachedImages(maxCache, onProgress);
```

- `maxCache` is the number of images to cache. This should be a positive integer.
- `onProgress` is an optional callback function that is called whenever the progress of caching images changes. It receives the current progress as a number between 0 and 1.

The returned Promise resolves when loadProgress reaches 1.

## Creating a Tarball with Images

Expand Down
3 changes: 0 additions & 3 deletions example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,5 @@
"license": "MIT",
"devDependencies": {
"vite": "^5.1.6"
},
"dependencies": {
"@mediamonks/fast-image-sequence": "^0.1.0"
}
}
6 changes: 3 additions & 3 deletions example/src/exampleConstructDestructTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ function createFastImageSequence(container) {
tarImageURLCallback: (i) => `${('' + (i + 1)).padStart(4, '0')}.jpg`,

// optional arguments:
wrap: Math.random() > .5, // default false
size: Math.random() > .5 ? 'cover' : 'contain', // default 'cover'
loop: Math.random() > .5, // default false
objectFit: Math.random() > .5 ? 'cover' : 'contain', // default 'cover'
fillStyle: '#00000000', // default #00000000
preloadAllTarImages: Math.random() > .5,
useWorkerForTar: Math.random() > .5, // default true
numberOfCachedImages: (1+Math.random()*32)|0, // default 32
maxCachedImages: (1+Math.random()*32)|0, // default 32
clearCanvas: Math.random() > .5, // default false
showDebugInfo: true,
});
Expand Down
6 changes: 3 additions & 3 deletions example/src/examplePlayBackwards.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ export async function initExamplePlayBackwards(container) {
// tarImageURLCallback: (i) => `${('' + (i+1)).padStart(4, '0')}.jpg`,

// optional arguments:
wrap: true, // default false
size: 'cover', // default 'cover'
loop: true, // default false
objectFit: 'cover', // default 'cover'
fillStyle: '#00000000', // default #00000000
preloadAllTarImages: false,
useWorkerForTar: true, // default true
numberOfCachedImages: 32, // default 32
maxCachedImages: 32, // default 32
clearCanvas: false, // default false
showDebugInfo: true,
});
Expand Down
19 changes: 13 additions & 6 deletions example/src/exampleStillImage.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
import { FastImageSequence } from '../../src/index';
import {FastImageSequence} from '../../src/index';

export async function initExampleStillImage(container) {
const fastImageSequence = new FastImageSequence(container, {
name: 'StillImageTest',
frames: 89,
imageURLCallback: (i) => `${('' + (i + 1)).padStart(4, '0')}.webp`,
tarURL: 'lowrespreviews.tar',
tarImageURLCallback: (i) => `${('' + (i+1)).padStart(4, '0')}.jpg`,
// tarURL: 'lowrespreviews.tar',
// tarImageURLCallback: (i) => `${('' + (i + 1)).padStart(4, '0')}.jpg`,

// optional arguments:
wrap: true, // default false
size: 'cover', // default 'cover'
loop: true, // default false
objectFit: 'cover', // default 'cover'
fillStyle: '#00000000', // default #00000000
preloadAllTarImages: false,
useWorkerForTar: true, // default true
numberOfCachedImages: 32, // default 32
maxCachedImages: 1, // default 32
clearCanvas: false, // default false
showDebugInfo: true,
});

await fastImageSequence.ready;

console.log('fastImageSequence loaded');

// now the first frame is loaded (numberOfCachedImages = 1), wait for 2 seconds, and then preload the other the frames
setTimeout(() => {
fastImageSequence.setMaxCachedImages(89, (progress) => console.log('preload progress:', progress)).then(() => {
console.log('all frames preloaded');
});
}, 2000);
}
10 changes: 5 additions & 5 deletions example/src/exampleWithControl.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ export async function initExampleWithControl(container) {
tarImageURLCallback: (i) => `${('' + (i+1)).padStart(4, '0')}.jpg`,

// optional arguments:
wrap: true, // default false
size: 'contain', // default 'cover'
loop: true, // default false
objectFit: 'contain', // default 'cover'
fillStyle: '#00000000', // default #00000000
preloadAllTarImages: false,
useWorkerForTar: true, // default true
numberOfCachedImages: 32, // default 32
maxCachedImages: 32, // default 32
clearCanvas: false, // default false
showDebugInfo: true,
});
Expand All @@ -28,7 +28,7 @@ export async function initExampleWithControl(container) {
fastImageSequence.progress = 0;

fastImageSequence.tick((dt) => {
if (fastImageSequence.isPlaying) {
if (fastImageSequence.playing) {
progress.value = fastImageSequence.progress;
}
});
Expand All @@ -43,7 +43,7 @@ export async function initExampleWithControl(container) {
fastImageSequence.stop();
});
progress.addEventListener('input', () => {
if (fastImageSequence.isPaused) {
if (fastImageSequence.paused) {
fastImageSequence.progress = progress.value;
}
});
Expand Down
28 changes: 28 additions & 0 deletions src/lib/DownloadFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export function downloadFile(url: string, onProgress?: (progress: number) => void): Promise<ArrayBuffer> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';

xhr.onprogress = function(event: ProgressEvent) {
if (event.lengthComputable && onProgress) {
const progress = event.loaded / event.total;
onProgress(progress);
}
};

xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(new Error(`Error ${xhr.status}: ${xhr.statusText}`));
}
};

xhr.onerror = function() {
reject(new Error('Request failed'));
};

xhr.send();
});
}
Loading

0 comments on commit 0373c79

Please sign in to comment.