Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

468
Views
How to load GIF Image using Canvas in NodeJs?

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
      });
    
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!