Using saveGif with graphics object in p5.js?

65 views Asked by At

I'm trying to save a series of images into a gif. I am trying to do this entirely in P5 without any other libraries or server side infrastructure. I got saveGif to work if I look at the main canvas, but as soon as I try with a graphics object, it breaks. I read using createCanvas multiple times can cause issues, but maybe I am supposed to do instance mode for this?

Anyways, this is what I'm trying right now:

function setup() {
    createCanvas(400, 400); // Set up a canvas
    // Example images to simulate Frame.frames
    let exampleFrames = [
        'path/to/image1.jpg',
        'path/to/image2.jpg',
        'path/to/image3.jpg'
    ];

    select("#saveGifButton").mouseClicked(function() {
        createGIF(exampleFrames);
    });
}

function createGIF(framePaths) {
    var images = [];
    var sumWidth = 0;
    var sumHeight = 0;

    // Load images and calculate dimensions
    for (var i = 0; i < framePaths.length; i++) {
        images[i] = loadImage(framePaths[i], img => {
            sumWidth += img.width;
            sumHeight += img.height;
        });
    }

    var picWidth = sumWidth / framePaths.length;
    var picHeight = sumHeight / framePaths.length;
    var tempGraphics = createGraphics(picWidth, picHeight);


    tempGraphics.saveGif("MyGif", images.length, {
                'units': 'frames'
            });
    for (var i = 0; i < framePaths.length; i++) {
        tempGraphics.clear();
        tempGraphics.image(images[i], 0, 0, picWidth, picHeight);
    }

    
    tempGraphics.remove();
}

So, when I tried with the graphics item, it gives this error:

 p5.js says: [p5.js, line 74975] 

Cannot read property of undefined. Check the line number in error and make sure the variable which is being operated is not undefined.

 + More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_property#what_went_wrong
p5.js:59804 ┌[http://127.0.0.1:5500/lib/p5.js:74975:27] 
     Error at line 74975 in addElement()
└[http://127.0.0.1:5500/lib/p5.js:75050:18] 
     Called from line 75050 in _main.default.createP()
└[http://127.0.0.1:5500/lib/p5.js:84471:32] 
     Called from line 84471 in _class._callee$()
└[http://127.0.0.1:5500/lib/p5.js:50400:25] 
     Called from line 50400 in tryCatch()
└[http://127.0.0.1:5500/lib/p5.js:50594:30] 
     Called from line 50594 in Generator.invoke [as _invoke]()
└[http://127.0.0.1:5500/lib/p5.js:50454:29] 
     Called from line 50454 in prototype.<computed> [as next]()
└[http://127.0.0.1:5500/lib/p5.js:84122:32] 
     Called from line 84122 in asyncGeneratorStep()
└[http://127.0.0.1:5500/lib/p5.js:84141:17] 
     Called from line 84141 in _next()
└[http://127.0.0.1:5500/lib/p5.js:84146:15] 
     Called from line 84146 in ()

GPT and googling failed me. I have no idea how else to handle this. Any ideas?

0

There are 0 answers