2
下面是我爲Phonegap項目開發的一段代碼。Uncaught TypeError:無法讀取undefined(array)的屬性「長度」
的jsfiddle:http://jsfiddle.net/wC79k/
我試圖繪製與供給的角度(sensorAngles陣列)的曲線。這個數組將通過藍牙更新(首先作爲字符串發送),因此如果接收到的數據沒有損壞(也就是每個陣列中沒有空或錯誤的元素,全長),我只需要更新曲線。
我現在正通過setTimeout通過更新角度陣列'模擬'藍牙串行更新。
當前,腳本按預期工作(曲線在損壞的數組/字符串時不會繪圖/更新,並在接收到非損壞數組後繼續更新),但是我收到上述錯誤(未捕獲的類型錯誤)。
它似乎與第26行有關,其中corrupt array使sensorAngles未定義(所以.length不起作用)。
for (var i = 0; i < (sensorAngles.length); i++){
sensorPos.push({
x: sensorPos[i].x - diffPos(sensorAngles[i]).dx,
y: sensorPos[i].y - diffPos(sensorAngles[i]).dy
});
}
我曾嘗試添加if語句,但曲線將不再更新。
我剛開始使用Javascript和Phonegap 2天前,所以任何幫助將是偉大的!
乾杯, JD
整個代碼:
var stage = new Kinetic.Stage({
container: 'myCanvas',
width: window.innerWidth,
height: window.innerHeight
});
var sensorLayer = new Kinetic.Layer();
/* initialise an empty array of all the angles */
var sensorAngles = [0, 0, 0, 0, 0, 0, 0, 0];
//var sensorPos = [];
/* divide each sensor distance segment by height of screen/window for
maximum amount of canvas being used */
var sensorDistance = (stage.getHeight()/((sensorAngles.length) + 2));
function diffPos(angle){ // angles in radians
return {
dx: sensorDistance * Math.sin(angle),
dy: sensorDistance * Math.cos(angle)
}
};
function calcSpline(sensorAngles){
sensorPos = [{x: (stage.getWidth()/2), y: (stage.getHeight() - sensorDistance)}];
for (var i = 0; i < (sensorAngles.length); i++){
sensorPos.push({
x: sensorPos[i].x - diffPos(sensorAngles[i]).dx,
y: sensorPos[i].y - diffPos(sensorAngles[i]).dy
});
}
return sensorPos;
};
calcSpline(sensorAngles);
var sensorPos = calcSpline(sensorAngles);
var spine = new Kinetic.Spline({
points: sensorPos,
stroke: 'red',
strokeWidth: 2,
lineCap: 'round',
tension: 0.3
});
sensorLayer.add(spine);
stage.add(sensorLayer);
function updateSpline(angles){
calcSpline(sanityCheck(angles));
spine.setPoints(sensorPos);
sensorLayer.draw();
};
function sanityCheck(data) {
data = data.split(",");
if (data.filter(function(n){return n}).length === sensorAngles.length) {
sensorAngles = data;
return sensorAngles;
}
}
setTimeout(
function() {
updateSpline("0.1,0.12,0.08,-0.2,0.1,0.85,0.1,-0.2")
},1000
);
setTimeout(
function() {
updateSpline("0.1,0.2,0.1,-0.1,0.1,0.1,0.1,-0.2")
},2000
);
setTimeout(
function() {
updateSpline("0.1,0.12,0.08,-0.2,0.1,0.85,0.1,-0.2")
},3000
);
setTimeout(
function() {
updateSpline("0.4,0.5,,-0.6,0.2,0.96,0.02,-0.01") //corrupt
},4000
);
setTimeout(
function() {
updateSpline("0.1,,0.08,-0.2,0.1,0.85,0.1,-0.2") // corrupt
},5000
);
setTimeout(
function() {
updateSpline("0.6,0.12,0.22,-0.2,0.1,0.85,0.1,-0.2")
},6000
);