我正在尝试在画布上绘制小图像,并为阵列中的每个人绘制一些文本。 我这样做
function drawPersonsOnCanvas(canvas, persons) {
var workIcon = '../images/work.png';
var partyIcon = '../images/party.png';
var context = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
// randomizePositions just put every object of array on random position inside canvas
persons = randomizePositions(persons, width, height);
for (var i in persons) {
var person= persons[i];
person['image'] = new Image();
person['image'].src = (person['type'] === 'work') ? workIcon: partyIcon;
person['image'].onload = function() {
context.drawImage(person['image'], person['x'], person['y']);
};
context.strokeText('person ' + person['status'], person['x'], person['y']);
}
}
我总是在地图上找到好位置上的所有文本,只有一个图像,x和y对所有人都不同(我有5个人在阵列中,我尝试过没有上传但是没有用)。有谁知道要改变什么,所以我为每个人拍了一张照片?
答案 0 :(得分:1)
到执行每个onload
时,您的person
变量已被重新分配给人员中的下一个元素。
所以你需要在onload
内创建一个新的人物变量。
为此,请为您的人['图像']添加指向正确人物的索引。
…
person['image'].index=i;
person['image'].src = (person['type'] === 'work') ? workIcon: partyIcon;
…
然后在onload中你可以重新创建正确的人:
var person=persons[this.index];
所以你的返工代码看起来像这样......还有一个小提琴:http://jsfiddle.net/m1erickson/xms9B/
function drawPersonsOnCanvas(canvas, persons) {
var workIcon = '../images/work.png';
var partyIcon = //'../images/party.png';
var context = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
// randomizePositions just put every object of array on random position inside canvas
persons = randomizePositions(persons, width, height);
for (var i in persons) {
var person= persons[i];
person['image'] = new Image();
person['image'].onload = function() {
var person=persons[this.index];
context.drawImage(person['image'], person['x'], person['y']);
context.strokeText('person ' + person['status'], person['x'], person['y']);
};
person['image'].index=i;
person['image'].src = (person['type'] === 'work') ? workIcon: partyIcon;
}
}