这个问题(我相信)与我之前遇到的变量范围(在 JavaScript 中)有关。我只是将您的代码作为一个函数移到了外部的 For 循环中,其中变量“i”现在是本地的,并且与使用该函数调用定义的对象保持一致。
function insideFor(i){
var data_value = data_array[i].value;
$('#legends').append('<div><span style="background: '+data_array[i].color+';"></span>'+data_array[i].data+'</div>')
var endAngle = startAngle + value_to_angle(data_value);
var arc = new Kinetic.Shape({
drawFunc: function(canvas) {
var context = canvas.getContext('2d');
context.beginPath();
context.arc(x, y, this.getAttrs().radius, this.getAttrs().startAngle, this.getAttrs().endAngle, false);
canvas.stroke(this);
},
fill: data_array[i].color,
stroke: data_array[i].color,
radius: radius,
startAngle: startAngle*0.0174532925,
endAngle: endAngle*0.0174532925,
strokeWidth: 20
});
startAngle = endAngle;
var circle_outer = new Kinetic.Shape({
drawFunc: function(canvas) {
var context = canvas.getContext('2d');
context.beginPath();
context.arc(x, y, this.getAttrs().radius, this.getAttrs().startAngle, this.getAttrs().endAngle, false);
canvas.stroke(this);
},
fill: '#ddd',
stroke: '#ddd',
radius: radius,
startAngle: 0,
endAngle: 360*0.0174532925,
strokeWidth: 20
});
layer.add(circle_outer);
layer.add(arc);
circle_outer.on('mouseover', function(e) {
(new Kinetic.Tween({
node: arc,
strokeWidth: 25,
easing: Kinetic.Easings['ElasticEaseInOut']
})).play();
});
circle_outer.on('mouseout', function(e) {
(new Kinetic.Tween({
node: arc,
strokeWidth: 20,
easing: Kinetic.Easings['ElasticEaseInOut']
})).play();
});
radius -= 30;
stage.add(layer);
}
for(var i = 0; i < data_array.length; i++){
insideFor(i);
}
这是更新的小提琴
http://jsfiddle.net/hnuf9/7/