简体   繁体   English

如何显示库存中的物品

[英]How to show items from inventory

How to make something like this to work? 如何使这样的东西起作用? I'm really new to programming and cant figure it out how to to make my inventory visible? 我真的是编程新手,无法弄清楚如何使我的库存可见?

Getting this error: Uncaught TypeError: Cannot read property 'img' of undefined image.(anonymous function).onload 收到此错误: 未捕获的TypeError:无法读取未定义图像的属性'img'。(匿名函数).onload

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var image = {};

function loadImage(name) {
    image[name] = new Image();
    image[name].onload = function () {
        //resourceLoaded();
    };
    image[name].src = "images/" + name;
}

var items = {
    knife: {
        name: "Knife",
        img: "knife.png"

    },
    sword: {
        name: "Sword",
        img: "sword.png"
    }
};

var inventory = []; //empty inventory

inventory.push(items.knife); //pickup a knife

for (var i = 0, len = inventory.length; i < len; i++) {
    loadImage(inventory[i].img);
    image[inventory[i].img].onload = function() {
            ctx.drawImage(image[inventory[i].img], 0, 0);
    }
}

Trying many things but cant understand anything better than this one :( Because im new to programing 尝试了很多事情,但没有比这更好的了:(因为我是编程新手

There's no block scope in JavaScript, only function scope. JavaScript中没有块作用域,只有函数作用域。 The i variable is the same everywhere in your snippet. i变量在代码段的任何地方都是相同的。 So when the image is loaded the i variable has the value of 2 ( inventory.length ). 因此,在加载图像时, i变量的值为2inventory.length )。

To do what you intend to do, you have to introduce a function scope. 要执行您打算做的事情,您必须引入一个功能范围。 One way to do it would be to do this : 一种方法是执行以下操作:

function createCallback(i) {
    loadImage(inventory[i].img);
    image[inventory[i].img].onload = function() {
        ctx.drawImage(image[inventory[i].img], 0, 0);
    }
}

for (var i = 0, len = inventory.length; i < len; i++) {
    createCallback(i);
}

You're trying to do the same thing twice in your for loop. 您试图在for循环中两次执行相同的操作。 That is, you should only have loadImage(inventory[i].img) in your for loop and move the ctx.drawImage call to within the loadImage() function: 也就是说,您应该只在for循环中包含loadImage(inventory[i].img)并将ctx.drawImage调用移至loadImage()函数中:

function loadImage(name) {
    image[name] = new Image();
    image[name].onload = function () {
        //resourceLoaded();
        ctx.drawImage(image[name], 0, 0);
    };
    image[name].src = "images/" + name;
}

This will draw the images on top of each other, though, if you add more to the inventory array. 但是,如果您向清单数组中添加更多图像,则会将图像彼此叠加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM