我在drawImage命令上得到“Uncaught TypeError”,因为我假设图片的url未正确提取。图片的路径是正确的(他们的文件夹与JavaScript文件在同一个文件夹中)。如何从JSON文件中引用单个属性?
提前致谢。
这是JSON:
{
"characters": [
{
"greekName": "Zeus",
"romanName": "Jupiter/Jove",
"description": "",
"picUrl": "pics/zeus.jpg"
},
{
"greekName": "Hera",
"romanName": "Juno",
"description": "",
"picUrl": "pics/hera.jpg"
},
{
"greekName": "Poseidon",
"romanName": "Neptune",
"description": "",
"picUrl": "pics/poseidon.jpg"
}
]
}
相关的html:
<canvas id="slideshow" width="400" height="400"></canvas>
以下是相关的.js代码:
var aImages = [];
canvas = document.getElementById('slideshow');
ctx = canvas.getContext('2d');
$(document).ready(function () {
$.getJSON("c.json?callback=?", function (data) {
$.each(data.characters, function (i, item) {
var oImg = new Image();
oImg.src = item.picUrl;
aImages.push(oImg);
}
);
});
});
ctx.drawImage(aImages[iCurSlide], 0, 0);
答案 0 :(得分:0)
将ctx.drawImage(aImages[iCurSlide], 0, 0);
置于getJSON
回调中。
var aImages = [];
canvas = document.getElementById('slideshow');
ctx = canvas.getContext('2d');
$(document).ready(function () {
// get json
$.getJSON("c.json?callback=?", function (data) {
$.each(data.characters, function (i, item) {
var oImg = new Image();
oImg.src = item.picUrl;
aImages.push(oImg);
});
// aImages is an array with elements
// go for each element from array, and draw it.
for (var i in aImages) {
ctx.drawImage(aImages[i], 0, 0);
}
});
});