8

我正在使用一些 javascript 来允许用户使用以下方法动态加载单击到画布元素的草图:

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。

4

3 回答 3

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;
};
于 2012-06-26T02:54:29.113 回答
3

我不熟悉 Processing.js,但该站点的示例代码有:

var canvas = document.getElementById("canvas1");
// attaching the sketchProc function to the canvas
var p = new Processing(canvas, sketchProc);
// p.exit(); to detach it

因此,在您的情况下,您需要在创建第一个实例时保留它的句柄:

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

当您准备“卸载”并加载新草图时,我猜(但不知道)您需要自己清除画布:

p1.exit();
var canvas = document.getElementById('canvas_id'); 
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
// Or context.fillRect(...) with white, or whatever clearing it means to you

然后,从事物的声音,您可以随意附加另一个草图:

var p2 = Processing.loadSketchFromSources('canvas_id', ['sketch2.pde']);

同样,我实际上并不熟悉该库,但这从文档中看起来很简单。

于 2012-06-25T09:33:46.120 回答
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);

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

于 2017-06-23T14:43:17.240 回答