问题
I am trying to call line info from a json object into a canvas using ajax. I'm new to json, so I'm not entirely sure how to go about doing this. Here's what I have so far.
JSON
{
"line": {
"width": 3,
"stroke": "#FFFFFF",
"x1": "640.386",
"y1": "258.163",
"x2": "816.364",
"y2": "258.163"
}
}
JS
$(document).ready(function(){
var canvas = document.getElementById("schematic_holder");
var ctx = canvas.getContext("2d");
$.ajax({
type: "GET",
dataType: "json",
url: "js/app/json/nst.json",
success: function(result){
$.each(result.line, function(){
console.log(result.line);
})
},
complete: function(){
console.log("Complete!");
}
})
})
HTML
<body>
<canvas id="schematic_holder"></canvas>
</body>
Right now, when I print to the console, I'm getting an undefined error. Am I calling the object wrong? I know how to get the lines to draw with canvas, I'm just confused about how to do so from a JSOn file. Thanks in advance.
回答1:
Try wrapping the entire json file in brackets [], like this
[{
"line": {
"width": 3,
"stroke": "#FFFFFF",
"x1": "640.386",
"y1": "258.163",
"x2": "816.364",
"y2": "258.163"
}
}]
来源:https://stackoverflow.com/questions/28972006/drawing-to-canvas-using-json-file