从画布动态“卸载”Processing JS草图

时间:2012-06-24 14:54:27

标签: javascript processing processing.js

我正在使用一些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。

3 个答案:

答案 0 :(得分: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;
};

答案 1 :(得分: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']);

当你准备好&#34;卸载&#34;并加载一个新的草图,我猜测(但不知道)你需要自己清理画布:

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']);

同样,我实际上并不熟悉该库,但从文档中可以看出这一点。

答案 2 :(得分:1)

截至处理.js 1.4.8,安德鲁接受的答案(以及我在这里找到的其他答案)似乎不再起作用了。

这对我有用:

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

    var canvas = document.getElementById('pjs')
    new Processing(canvas, scriptText);

其中pjs是正在运行scrips的canvas元素的id。