Drawing to canvas using JSON file

谁说胖子不能爱 提交于 2020-01-17 12:14:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!