ReferenceError: imageNoteTaker is not defined
layer.add(imageNoteTaker);
尝试使用kinetic.js进行简单的补间时会出现上述错误。我的项目正在尝试将音频与动画同步。播放音频时经常调用'sync()'功能。当音频达到4.85秒时,此函数会调用函数'animation1()'。该函数中的代码导致了我的问题。
这里尝试执行'layer.add(imageNoteTaker);'在行中,未定义变量imageNoteTaker。但是在image.onload()方法中,定义imageNoteTaker的代码出现在它之前。但控制并没有完全忽略这一点。
以下部分出现错误:
var imageObj = new Image();
imageObj.src="images/note_taker.png";
imageObj.onload = function(){
imageNoteTaker= new Kinetic.Image({
x: stage.getWidth()/2.35,
y: stage.getHeight()/1.5,
width: 75*202/100,
height:75*350/100,
image: imageObj
});
}
layer.add(imageNoteTaker);
layer.draw();
这是我的全部代码:
//Variable Declaration
var audioId=document.getElementById("audioId");
var currentAnimation="none";
//Kinetic Library Setup
var stage = new Kinetic.Stage({
container: 'moving',
width: 800,
height: 545
});
//Layer Declaration
var layer = new Kinetic.Layer();
stage.add(layer);
//Function called 3-4 times in a second while playing audio
var sync=function(){
var currentPosition = audioId.currentTime;
console.log("direct from audio tag: "+currentPosition);
currentPosition=currentPosition.toFixed(2);
console.log("after rounding : "+currentPosition);
switch(true){
case rangeGenerator(5.85,currentPosition):
console.log(currentAnimation + "is CurrentAnimation");
if(currentAnimation!="animation1"){
currentAnimation="animation1";
animation1();
}
break;
default:
console.log("default");
}
};
//Function used in sync() function to check a value is in particular range
var rangeGenerator=function(value,currentPosition){
if(Math.abs(currentPosition-value)<.25){
console.log(currentPosition+"dfd"+"value");
return true;
}
else{
return false;
}
};
//Function that triggers the first animation; NoteTaker
var animation1=function(){
console.log("Animation1");
//Image Note_Taker Initialisation
var imageObj = new Image();
imageObj.src="images/note_taker.png";
imageObj.onload = function(){
imageNoteTaker= new Kinetic.Image({
x: stage.getWidth()/2.35,
y: stage.getHeight()/1.5,
width: 75*202/100,
height:75*350/100,
image: imageObj
});
}
layer.add(imageNoteTaker);
layer.draw();
console.log("Tweening...");
var tween = new Kinetic.Tween({
node: imageNoteTaker,
duration: 1,
x: stage.getWidth()/2.35,
y: stage.getHeight()/4.0
});
tween.play();
};
//On window resize, resizing stage too.
window.onresize = function(event) {
stage.setWidth((window.innerWidth / 100) * 80); // 80% width again
};
如何删除此错误?
答案 0 :(得分:0)
通常在加载Object时调用onload方法。加载完成后,将触发加载事件。然后该事件触发该方法。
如果是这样,当您调用animation1函数时,应该在执行代码时跳过onload方法。因此,未定义变量。
我建议在类中使变量imageNoteTaker全局 - 将其置于currentAnimation的定义之下 - 并且仅在设置变量时调用layer.add(...)。