Dynamically “unload” a Processing JS sketch from canvas

前端 未结 3 1826
攒了一身酷
攒了一身酷 2021-01-02 15:28

I\'m using some javascript to allow users to dynamically load a sketch on click to a canvas element using:

Processing.loadSketchFromSources(\'canvas_i

3条回答
  •  感情败类
    2021-01-02 16:24

    In case someone else comes looking for the solution, here's what I did that worked. Note that this was placed inside a closure (not included here for brevity) -- hence the this.launch = function(), blah blah blah... YMMV.

    /**
     * Launches a specific sketch. Assumes files are stored in
     * the ./sketches subdirectory, and your canvas is named g_sketch_canvas
     * @param {String} item The name of the file (no extension)
     * @param {Array} sketchlist Array of sketches to choose from
     * @returns true
     * @type Boolean
     */
    this.launch = function (item, sketchlist) {
        var cvs = document.getElementById('g_sketch_canvas'),
            ctx = cvs.getContext('2d');
        if ($.inArray(item, sketchlist) !== -1) {
            // Unload the Processing script
            if (Processing.instances.length > 0) {
                // There should only be one, so no need to loop
                Processing.instances[0].exit();
                // If you may have more than one, then use this loop:
                 for (i=0; i < Processing.instances.length; (i++)) {
                //  Processing.instances[i].exit();
                //}
            }
            // Clear the context
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.clearRect(0, 0, cvs.width, cvs.height);
            // Now, load the new Processing script
            Processing.loadSketchFromSources(cvs, ['sketches/' + item + '.pde']);
        }
        return true;
    };
    

提交回复
热议问题