示例对象:
images {"foo":"bar.jpg",...}
如何将此对象转换为要使用的图像文件列表,
ctx.drawImage(images.foo,x,y)
没有创建新对象?
答案 0 :(得分:0)
一种方法:
var images = { "foo": "bar.jpg" }
for (var imageKey in images) {
images[imageKey] = ctx.drawImage(images[imageKey],x,y)
}
答案 1 :(得分:0)
正如您在评论中所说,您希望在函数中发生这种情况,并且您希望将图像路径变为Image
类型的对象,我认为这就是您要寻找的内容:
var images = { "foo": "bar.jpg" };
function transformImagePaths(images){
Object.keys(images).forEach(key => {
let imagePath = images[key];
images[key] = new Image();
images[key].src = imagePath;
});
}
当您将images
对象传递给该函数时,它将遍历其键,并通过用图像替换路径来重新分配每个键。
答案 2 :(得分:0)
// first proving approach
var imageMap = {
"foo": "bar.jpg",
"baz": "biz.jpg"
};
console.log('imageMap : ', imageMap);
Object.keys(imageMap).forEach(function (imageKey) {
var img = (new Image);
img.src = imageMap[imageKey];
imageMap[imageKey] = img;
});
console.log('imageMap : ', imageMap);
// final iteration
var imageMap = {
"foo": "bar.jpg",
"baz": "biz.jpg"
};
console.log('imageMap : ', imageMap);
function assignImageToBoundMap(key) {
var img = (new Image);
img.src = this[key];
this[key] = img;
}
function reassignImageMap(map) {
Object.keys(map).forEach(assignImageToBoundMap, map);
}
reassignImageMap(imageMap);
console.log('imageMap : ', imageMap);
.as-console-wrapper { max-height: 100%!important; top: 0; }