javascript - 如何从文本输入中评估 JavaScript 函数

标签 javascript parsing three.js

我有一个在 THREE.js 中运行的浏览器内粒子引擎。我想添加动画功能,所以我有一个包含代码的文本输入,应该从我的“动画”函数中调用它来更新粒子发射器的位置和其他信息。 https://i.imgur.com/vguWZAq.jpg

function animate() {

    time = Date.now();

    runCustomAnimateScript();

    for(var i = 0; i < emitters.length; i++){
        emitters[i].updateParticles(deltaTime);
    }

    render();

    requestAnimationFrame( animate );
}

function runCustomAnimateScript(){
    //Filled from text input after updateCustomAnimateScript is called
    //Called from within animate (which is run every frame)
}

function updateCustomAnimateScript(){
    //Parse document.querySelectorAll("textarea[name='customAnimateScript']").value 
    //into a script, and enter it into runCustomAnimateScript
}

目前我无法将此文本输入转换为可执行的 JavaScript 函数。我很惊讶以前没有人尝试过这样做,或者至少没有发布过相关信息?

最佳答案

评估任意代码的旧方法是使用 eval()方法。

更好的方法是使用 Components.utils.evalInSandbox ,但支持可能有限。

function runCustomAnimateScript(){
   const sandbox = new Components.utils.Sandbox("http://www.your-url.com/");
   let result = Components.utils.evalInSandbox(document.querySelectorAll("textarea[name='customAnimateScript']").value , sandbox);
}

关于javascript - 如何从文本输入中评估 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47701427/

相关文章:

javascript - A 形框架中的灯光根据与它们的距离而产生条纹伪影

javascript - 平滑滚动脚本阻止链接

javascript - 如何动态更改 Vue.js 转换

javascript - 在使用 D3.js fork 3D Force-Directed Graph 创建的 2D 图形上的鼠标左键上添加鼠标平移

javascript - 场景中的工件 Three.js/editor

javascript - 一次加载全部 XML 还是一点一点加载更快?

javascript - 括号内带有参数的 REST API URL 资源

javascript - ChaiJS 期望构造函数抛出错误

C# 解析对象的 JSON 数组

iphone - 如何根据 Xcode 中的当前日期解析不同的文件?