I'm using MacOS for testing it. I have giflib installed on my mac as per the documentation mentioned in Canvas NPM Package .
I'm able to serve Images perfectly with canvas, but I'm unable to serve GIFs to the browser using Canvas. There are no error logs as well.
Here is my code:
app.get('/media', function(req, res) {
const { createCanvas, loadImage, giflib } = require('canvas')
const canvas = createCanvas(600, 400)
const ctx = canvas.getContext('2d')
const imagePath = loadImage('https://via.placeholder.com/200x200.png')
const gifPath = loadImage('https://www.hubspot.com/hubfs/Smiling%20Leo%20Perfect%20GIF.gif')
gifPath.then((image) => {
// do something with image
canvas.toBuffer((err2, buf) => {
if (err2) {
console.log("To Buffer Error>>>>>>", err2)
}
else
{
res.writeHead(200, {'Content-Type': 'image/gif'});
res.end(buf, 'binary');
}
}, 'image/gif', { quality: 0.95 })
}).catch(err => {
console.log('oh no!', err)
})
})
The code works if I use imagePath and mimeType as image/png.
Could someone point me in the right direction?
I think you cannot handle the animated gif with a single canvas. You should either
create an animated canvas as described in https://stackoverflow.com/a/10180164/11009351 if you want to modify the image
or simply write the image as a byte stream as follows
const http = require("http");
const express = require("express");
const request = require("request");
const app = express();
const server = http.createServer(app);
server.listen(8080);
app.get("/media", function (req, res) {
const x = request(
"https://www.hubspot.com/hubfs/Smiling%20Leo%20Perfect%20GIF.gif"
);
x.pipe(res);
});