0

我正在尝试在画布上绘制小图像,并为我在数组中的每个人绘制一些文本。我正在这样做

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 个人在数组中,我尝试过并且没有 onload,但它不起作用)。有谁知道要改变什么,所以我为每个人拍一张照片?

4

1 回答 1

1

每次onload执行时,您的person变量已经被重新分配给 people 中的下一个元素。

所以你需要在里面创建一个新的 person 变量onload

为此,请向您的 person['image'] 添加一个指向正确人员的索引。

    …
    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;
    }
}
于 2013-05-03T16:56:32.090 回答