[英]Processing.getInstanceById(id); works with one function, undefined for another?
继http://processingjs.org/articles/PomaxGuide.html在网页上使用“处理”草图之后,我的一项功能完美地利用了这一点:
function drawSomething() {
// some calculations
var pjs = Processing.getInstanceById('canvasID');
var number = 5 // placeholder result of calculations
pjs.drawText(number);
}
还有另一个函数drawSomethingElse,相同的pjs变量定义日志:
TypeError: pjs is undefined
所有代码都包装在docReady和drawSomething();中。 页面加载时调用:
$(document).ready(function(){
// do lots of stuff
drawSomethingElse();
}
javascript中的范围是这样的。 如果要声明var
或function
另一个函数内部它只是这个函数内部可见
function outerScope(){
var outerVariable = "is defined in outer scope";
function innerScope(){
var innerVariable = "is defined in inner scope";
console.log(outervariable); //innerScope can see outerVariable (through a closure)
}
console.log(innerVariable) //=undefined outerScope can't see innerVariable
console.log(outerVariable) //outerScope can still see outerVariable
}
console.log(outerScope) //= function, global scope can see outerScope
console.log(outerVariable) //=undefined but global scope can't see inside outerScope
console.log(innerScope) //= undefined, therefore it can't see innerScope
console.log(innerVariable) //=undefined and of course not into inner scope
所有功能(包括jQuery功能)都是如此,它们也不例外。 因此,这就是为什么您必须在想要使用作用域“层”的作用域中定义var
的原因。 为了不污染全局范围,您可以将内容包装到这些匿名函数中,而只是添加范围“层”
无论添加多少层,该模型始终适用。 您将始终能够了解行为。 (顺便说一句,请始终使用console.log 来检查所有不确定的内容,这有助于查找错误。您可以越精确地回答解决方案的问题,就越知道如何解决该问题)
适应您对范围的了解,并且由于您没有在当前范围内定义Processing
,因此您知道它必须在全局范围内,这意味着您可以打开浏览器控制台,仅打开console.log(Processing)
并可能调用Processing.getInstanceById()
方法Processing.getInstanceById()
自己在控制台中几次Processing.getInstanceById()
。 也许不是画布ID,而是定义实例名称的草图名称。 试试看。
由于您现在知道要通过JavaScript获取实例时尚未加载.pde草图,因此有几种选择。 最简单的方法是使草图成为文档的一部分,因此$(document).ready()仅在加载处理和草图时才触发并执行JavaScript。
通常,处理过程会检查画布上的custom data-processing-sources
属性,并发送异步请求文件(您的草图)。 但是由于它是异步的,因此它不是文档加载的一部分,因此文档已准备好,但草图还没有。
如果您改为将草图代码放在文档内的脚本标签中,则文档在加载之前无法准备就绪。 您还需要设置mime类型,否则浏览器会认为这是javascript并抛出错误。 它不会改变任何其他内容,而只是设置处理草图的另一种方法。
<script type="text/processing" data-processing-target="canvasID">
//your sketch code
</script>
<canvas id="canvasID"></canvas>
对于您来说,仍然可以从外部加载草图,这是设置草图的第三种方式,有些混乱。 删除整个脚本标签和草图。
跳过data-processing-target和data-processing-sources属性,而不是pjs = Processing.getInstanceById
编写
$(document).ready(function(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "yourSketch.pde");
xhr.onload = function(){
var code = xhr.response;
var canvas = document.getElementById("canvasID")
pjs = new Processing(canvas,code);
//rest of your code
}
xhr.send();
});
注意:如果您通过file://协议在本地查看您的网站,则此技术将无效
pjs作用域是drawSomething函数,用于在其他函数中使用它会像这样更改代码
(function() {
var pjs = Processing.getInstanceById('canvasID');
function drawSomething() {
var number = 5 // placeholder result of calculations
pjs.drawText(number);
}
function someotherfunction() {
drawSomething();
}
}());
现在您可以在此anon函数中的任何地方使用pjs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.