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

Dynamically "unload" a Processing JS sketch from canvas

本文关键字:卸载 处理 JS 草图 布动态 动态      更新时间:2023-09-26

我正在使用一些javascript来允许用户在单击画布元素时使用以下内容动态加载草图:

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

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

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

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

我不是JS专家,但我已经尽力查看处理.js源代码,以查看可能存在的其他功能,但是我遇到了障碍。我想也许我可以看看 Processing.Sketches.length 看看是否已经加载了某些东西,但简单地将其从数组中弹出似乎不起作用(没想到会)。

我正在使用处理JS 1.3.6。

万一其他人来寻找解决方案,这就是我所做的工作。请注意,这是放在闭包中的(为简洁起见,此处未包含) - 因此this.launch = function(),等等等等...扬子晚报.

/**
 * 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;
};

我不熟悉处理.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']);

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

截至处理.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 的画布元素的 ID。