我有一个在 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/