Giter Club home page Giter Club logo

apng-js's Introduction

apng-js

apng-js provides functions for parse and render animated PNG's (APNG).

Demo page

https://davidmz.github.io/apng-js/

Usage

npm install apng-js

API

parseAPNG(buf: ArrayBuffer): (APNG|Error)

Default exported function. Parses APNG data, returns APNG object (see below) or Error. This function can be used in node.js environment. Object methods relies on browser features (canvas, requestAnimationFrame…) and should work only in browser.

Usage:

import parseAPNG from 'apng-js';

const apng = parseAPNG(buffer);
if (apng instanceof Error) {
    // handle error
}
// work with apng object

isNotPNG(err: Error): boolean

Checks if Error is 'Not a PNG' error.

isNotAPNG(err: Error): boolean

Checks if Error is 'Not an animated PNG' error.

Classes

APNG

Structure of APNG file.

class APNG {
    width: number     // with of canvas, pixels
    height: number    // height of canvas, pixels
    numPlays: number  // number of times to loop animation (0 = infinite looping)
    playTime: number  // total duration of one loop in milliseconds
    frames: Frame[]   // array of frames

    // Methods
    createImages(): Promise // create imageElement's for all frames
    getPlayer(context: CanvasRenderingContext2D, autoPlay: boolean = false): Promise.<Player>
        // Create Player (see below) on given context and start playing
        // if autoPlay is true.
}

Frame

Individual APNG frame.

class Frame {
    left: number      // left offset of frame, pixels
    top: number       // top offset of frame, pixels
    width: number     // with of frame, pixels
    height: number    // height of frame, pixels
    delay: number     // time to show frame in milliseconds
    disposeOp: number // type of dispose operation (see APNG spec.)
    blendOp: number   // type of blend operation (see APNG spec.)
    imageData: Blob   // image data in PNG (not animated) format
    
    imageElement: HTMLImageElement // image data rendered as HTML Image element.
                                   // This field is null right after 'parse',
                                   // use Frame.createImage() or APNG.createImages()
                                   // to fill this field.
                                   
    // Methods
    createImage(): Promise // create imageElement for this frame
}

Player

Player renders APNG frames on given rendering context and plays APNG animation.

class Player {
    context: CanvasRenderingContext2D
    playbackRate: number = 1.0 // animation playback rate
           
    currFrameNumber: number // current frame number (read only)
    currFrame: Frame        // current frame (read only)
    paused: boolean         // playback is paused (read only)
    ended: boolean          // playback is ended (read only)

    // Methods
    play()      // start or resume playback
    pause()     // pause playback
    stop()      // stop playback and rewind to start
    
    renderNextFrame()       // move to next frame and render it on context
                            // Use this method to manual, frame by frame, rendering.
}

Player object is an EventEmitter. You can listen to following events:

  • play — playback started;
  • frame — frame played (frame number passed as event parameter);
  • pause — playback paused;
  • stop — playback stopped;
  • end — playback ended (for APNG with finite count of plays).

apng-js's People

Contributors

davidmz avatar dependabot[bot] avatar wwzzyying avatar xiaoxiangmoe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

apng-js's Issues

Updating and contributing

Hello David,

apng-js is a great tool for manipulating apng files, thank you for this!

The code has not been updated for 4 years now.
Some forks contain interesting updates or additions (https://github.com/WiseLee0/apng-js-mini) and there are some features that I am about to add too (reverse play using negative values of playbackRate).

I don't know what your current situation is but would you agree to give some help by merging interesting forks, including the one I am working on? I think it is always better to contribute to the original project.

Best regards,
Anthony

Stop/play parsed aPNG

Hey, after running the below code I'm able to see the image details, but could you tell me how can I stop or play again some animation? I can see the play method, but I'm unable to do trigger it:

APNG.parseURL(src).then(function(data) {
  console.log(data);
});

Should I somehow assign it to a variable like const player = APNG.parseURL(src); and then use it by player.play(); if needed or how it works?

Player scaling

The player currently doesn't scale the content of the canvas to the width & height of the canvas. This is relevant if i.e. the content of the buffers is larger than the canvas it's supposed to be rendered on.
Can this be added, so that the canvas scales its content?

Use in node.js

Hi,
I'm trying to use the parseAPNG() function in node.js but keep receiving the 'Not a PNG' error.
I'm reading the .apng file to a 'Buffer', then converting it to an 'ArrayBuffer' before sending to parseAPNG().
Am I doing something wrong?
Thanks !

Build failing

The file parser.d.ts has a syntax error

import { APNG, Frame } from './structs';
export declare function isNotPNG(err: unknown): boolean;
export declare function isNotAPNG(err: unknown): boolean;
/**
 * Parse APNG data
 *
 */
export default function parseAPNG(buffer: ArrayBuffer): Error | APNG;

// export type APNG,   << HERE
// export type Frame;  << HERE

Commenting out the last two lines allows the project to be compiled.

Extract from my package.json:

 "dependencies": {
    "@angular/animations": "~9.0.0",
    "@angular/cdk": "^10.1.2",
    "@angular/common": "~9.0.0",
    "@angular/compiler": "~9.0.0",
    "@angular/core": "~9.0.0",
    "@angular/forms": "~9.0.0",
    "@angular/localize": "^9.0.5",
    "@angular/platform-browser": "~9.0.0",
    "@angular/platform-browser-dynamic": "~9.0.0",
    "@angular/router": "~9.0.0",
    "apng-js": "^1.1.1",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },

Transparency applied to non-changed pixels?

Hi,
I'm having a weird issue.
When I call my apng with an img tag it looks fine.
When I display it after parsing with the parseAPNG() function it seems like that all the pixels that aren't changing from frame to frame became transparent and discarded (images cropped).
Is there a way to avoid this?
Thanks :)
Screen Shot 2022-01-06 at 4 23 15 PM

Simple implementation

Hi there! Thanks so much for making this library!

I'm looking for a drop-dead simple way to use this library, but it appears to be wrapped in Webpack and importing multiple files.

Do you have a completely compiled file, (maybe even minified) that I can pop into my site and it will just target the png on the page.

I'm trying to pause a png after 5 seconds and/or click.

Any help would be great. I've read your docs about vanilla implementation, but the file just won't play nice since they require imports.

Add type for this project.

I want to help provide type support for this repo. May I write a .d.ts for this or help to change the whole project from JavaScript to TypeScript?

How do you include this on a web page?

I want the ability to play/pause the APNG on a webpage. I am having trouble understanding from the instructions on the readme exactly how you get an APNG on the webpage and use this library to control it.

I saw the demo and see that it does this, but the index.js doesnt look like your documentation.

Possible to place the animation somewhere else on canvas?

Hi @davidmz,

really nice work you did with this library! Many thanks so far, it works great.

One question though, is it possible to place the animation somewhere else on the canvas instead of 0:0? I'm not a canvas-expert and it your library doesn't provide something like this, or?

Many thanks in advance and cheers, Christian

PNG to APNG in NodeJS?

I'm using NodeJS and just want to read in a bunch of png files and output them to apng, i'm not interested in anything browser related nor am I interested in reading in an existing apng file. I thought your program could do this but maybe i'm wrong, Is your program just for managing existing apng files?

Seek to a certain frame

Awesome project, thanks!

Some of my animations actually have a "freeze frame" which isn't 0, so something like seek(46) would be very helpful.

Right now I may createImage for that frame and draw it myself on the context, it's dirty. WDYT?

i try to use getPlayer but receive an err Image creation error(in react)

async createApngPlayer(url, ctx, options = {}) {
const imgBuffer = await this.getImgBuffer(url);
const apng = parseAPNG(imgBuffer);
Object.keys(options).forEach(key => {
apng[key] = options[key];
});
// apng.createImages().then(()=>{
// console.log();
// }).catch((err) => {
// console.log(err,'播放err');
// });
apng.getPlayer(ctx).then(player1=>{
console.log(player1, '播放');
player1.play();
}).catch(err => {
console.log(err, '播放');
});
// const player = await apng.getPlayer(ctx);
console.log(player, '播放');
return player;
}

i can log apng but this code cannot return player with err 'Image creation error'.

if createImages first ,err in getPlayer will be 'Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D'
and err in createImanges 'Image creation error'.

Modify and export new APNG

I have to say this is such an amazing little project you have here! I'm very new to all of this and this was really helpful. On that I have a suggestion: what about being able to modify the field values like the duration, the size, etc, so you can export a new APNG? Have you ever considered trying to do that?

Additionally, would you add a way to export the frames individually?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.