Canvas只绘制地图上循环的最后一个元素

Canvas only drawing last element of loop on map

本文关键字:最后一个 元素 循环 绘制 地图 Canvas      更新时间:2023-09-26

我使用Icon。帆布在传单地图上用帆布画标记。我遇到了问题,我假设这与"循环关闭"有关,但我似乎无法使用任何其他解决方案,因为在创建一个普通画布和它的上下文和我正在做的事情(画布元素和ctx是由图标创建的)的差异。帆布库)。

for (var park in parksMap) {
                var circle = new L.Icon.Canvas({
                    iconSize: new L.Point(50, 50)
                });

                var item = parksMap[park];
                var total = item.kpis.availability.online + item.kpis.availability.offline + item.kpis.availability.noComm;
                var greenSize = item.kpis.availability.online * 2 / total;
                var redSize = item.kpis.availability.offline * 2 / total;
                console.log('OUTSIDE');
                console.log(item);
                circle.draw = function (ctx, w, h) {
                    console.log('INSIDE');
                    console.log(item);
                    setUpParkForStatus(item, ctx, greenSize, redSize);
                    parkWindConstructor(ctx);
                    ctxArray.push({
                        id: item.id,
                        ctx: ctx
                    });
                } ... 
(code continues on to create the actual markers)
}

setUpParksStatus是具有绘图实际代码的函数。以下是控制台的结果。日志以便更好地理解:

 OUTSIDE
 park1
 OUTSIDE
 park2
 INSIDE
 park2
 INSIDE
 park2

您可以使用返回包含当前逻辑的函数的IIFE,因此当时的值不会受到循环的影响。

编辑:当进入ES2015时,您可以使用let/const代替var来实现您当前的代码,因为它是block-scoped而不是function-scoped

If库可以使用下划线。如果不能,你仍然可以使用Object.keys()作为Array获取键,然后使用.forEach进行循环,所有这些方法都可以防止在循环中获得的值随着循环的推进而改变。

失败的演示,和IIFE修复:

'use strict';
var obj = {
  'a': 1,
  'b': 2,
  'c': 3
};
var funcArr1 = [];
var funcArr2 = [];
var k, func1, func2;
for (k in obj) {
  // Way 1, all point to last.
  func1 = function() {
    console.log(k, obj[k]);
  };
  
  // Snapshot it
  // The wrap function will be called imediately, and it'll return the function similar to func1
  // But the outer function creates a scope, which stores the k(and rename it to v to avoid ambiguous)
  // So all the func2s will point to each key in obj instead of last.
  func2 = (function(v) {
    return function() {
      console.log(v, obj[v]);
    };
  })(k);
  
  funcArr1.push(func1);
  funcArr2.push(func2);
}
// IN ES2015, you can use let to achieve:
var funcArr3 = [];
var func3;
// The let, unlike var, is block scoped, so it can achieve what you expect in simpler form.
for (let m in obj) {
  func3 = function() {
    console.log(m, obj[m])
  }; 
  funcArr3.push(func3);
}
// To loop object with .forEach, which works on array.
var funcArr4 = [];
Object.keys(obj).forEach(function(key, index) {
  funcArr4.push(function() {
    console.log(key, obj[key]);
  });
});
var i, length = funcArr1.length;
for (i = 0; i < length; ++i) {
  console.log('Way1');
  funcArr1[i]();   // All of it will log c, 3, as k is pointing to c when exit the loop.
  console.log('Way2');
  funcArr2[i]()  // Because we use a function to keep k, it'll log what we expect.
  
  console.log('Way ES2015');
  funcArr3[i]();  // Because we use a function to keep k, it'll log what we expect.
  console.log('Way forEach');
  funcArr4[i]();  // Because we use a function to keep k, it'll log what we expect.
}

Demo with forEach:

var obj = {
  'a': 1,
  'b': 2,
  'c': 3
};
var funcArr = [];
Object.keys(obj).forEach(function(key, index) {
  funcArr.push(function() {
    console.log(key, obj[key]);
  });
});
var i, length = funcArr.length;
for (i = 0; i < length; ++i) {
  console.log('Way forEach');
  funcArr[i]();  // Because we use a function to keep k, it'll log what we expect.
}

使用letES2015的演示(这需要一些非常现代的浏览器版本才能使代码片段工作),但是有能够将ES2015语法编译为ES5的转译器,以便在大多数浏览器上工作(例如:g:巴别塔):

'use strict';  // This make chrome to accept some ES2015 syntax
const obj = {
  'a': 1,
  'b': 2,
  'c': 3
};
// IN ES2015, you can use let to achieve:
let funcArr = [];
// The let, unlike var, is block scoped, so it can achieve what you expect in simpler form.
for (let m in obj) {
  funcArr.push(function() {
    console.log(m, obj[m])
  });
}
for (let i = 0, len = funcArr.length; i < len; ++i) { 
  console.log('Way ES2015');
  funcArr[i]();  // Because we use a function to keep k, it'll log what we expect.
}

你可以对circle.draw做类似的事情:

// Now the current value that may be used by the callback won't change as loop advanced.
circle.draw = (function(item, total, greenSize, redSize) {
  return function (ctx, w, h) {
        console.log('INSIDE');
        console.log(item);
        setUpParkForStatus(item, ctx, greenSize, redSize);
        parkWindConstructor(ctx);
        ctxArray.push({
            id: item.id,
            ctx: ctx
        });
  };
})(item, total, greenSize, redSize);