https://github.com/codeadamca/javascript-canvas-to-gif
A basic example of creating and displaying a GIF using canvas content.
https://github.com/codeadamca/javascript-canvas-to-gif
base64 gif gifencoder javascript lzw-encoding
Last synced: 12 months ago
JSON representation
A basic example of creating and displaying a GIF using canvas content.
- Host: GitHub
- URL: https://github.com/codeadamca/javascript-canvas-to-gif
- Owner: codeadamca
- Created: 2023-05-20T03:23:48.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2025-01-26T22:20:16.000Z (about 1 year ago)
- Last Synced: 2025-01-26T23:20:39.287Z (about 1 year ago)
- Topics: base64, gif, gifencoder, javascript, lzw-encoding
- Language: HTML
- Homepage:
- Size: 9.77 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Creating a GIF using JavaScript
A basic example of creating and displaying an animated GIF using canvas content.
1. Include the necessary libraries:
```html
```
2. Add multiple canvases to the document:
```html
```
3. Add a container:
```html
```
4. Use JavaScript to add the content from the canvases to a `gif`:
```javascript
const canvas1 = document.getElementById('canvas1');
const context1 = canvas1.getContext('2d');
context1.fillStyle = "red";
context1.fillRect(0, 0, 100, 100);
const canvas2 = document.getElementById('canvas2');
const context2 = canvas2.getContext('2d');
context2.fillStyle = "green";
context2.fillRect(0, 0, 100, 100);
const canvas3 = document.getElementById('canvas3');
const context3 = canvas3.getContext('2d');
context3.fillStyle = "blue";
context3.fillRect(0, 0, 100, 100);
let encoder = new GIFEncoder();
encoder.setRepeat(0);
encoder.setDelay(500);
encoder.start();
encoder.addFrame(context1);
encoder.addFrame(context2);
encoder.addFrame(context3);
encoder.finish();
let binaryData = encoder.stream().getData();
let dataUrl = 'data:image/gif;base64,'+encode64(binaryData);
const image = document.createElement("img");
image.src = dataUrl;
document.getElementById('container').appendChild(image);
```
The full working code is in the `canvas-to-gif.html` file.
***
## Repo Resources
* [LZW Encoder](https://gist.github.com/revolunet/843889)
* [NewQuant](https://github.com/unindented/neuquant-js)
* [gifencoder](https://github.com/eugeneware/gifencoder)
* [base54.js](https://github.com/dankogai/js-base64)