从画布动态"卸载"Processing JS草图

And*_*oni 7 javascript processing processing.js

我正在使用一些javascript来允许用户使用以下命令动态加载素描到click元素:

Processing.loadSketchFromSources('canvas_id',['sketch.pde']);

如果我将Processing.loadSketchFromSources(...)调用第二个(或第三个......)时间,它会将第二个(或第三个......).pde文件加载到画布上,这正是我所期望的.

我希望用户能够单击另一个链接来加载不同的草图,有效地卸载前一个草图.有没有我可以调用的方法(或者我可以使用的技术)来检查Processing是否有另一个草图运行,如果有,请告诉它先卸载它?

是否有某种Processing.unloadSketch()方法我忽略了?我可以简单地删除画布DOM对象并重新创建它,但是当我需要针时,(1)似乎使用锤子,(2)它会导致我想避免的屏幕闪烁.

我不是JS专家,但我已经尽力查看processing.js源代码,看看其他功能可能存在,但我还是碰壁了.我想也许我可以看看Processing.Sketches.length来查看是否已经加载了某些东西,但只是将它从阵列弹出似乎不起作用(不认为它会).

我正在使用ProcessingJS 1.3.6.

And*_*oni 5

如果其他人来寻找解决方案,这就是我所做的工作.请注意,这是放在一个闭包内(为简洁起见,这里不包括) - 因此this.launch = function(),等等等等等等...... 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;
};
Run Code Online (Sandbox Code Playgroud)


a.l*_*l.e 0

从processing.js 1.4.8开始,Andrew接受的答案(以及我在这里找到的其他答案)似乎不再有效。

这对我有用:

    var pjs = Processing.getInstanceById('pjs');
    if (typeof pjs !== "undefined") {
      pjs.exit();
    }

    var canvas = document.getElementById('pjs')
    new Processing(canvas, scriptText);
Run Code Online (Sandbox Code Playgroud)

其中pjs是运行脚本的画布元素的 id。