使用JSON文件绘制到画布

时间:2021-03-13 16:51:42

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.

我试图使用ajax从json对象调用行信息到画布。我是json的新手,所以我不完全确定如何做到这一点。这是我到目前为止所拥有的。

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.

现在,当我打印到控制台时,我收到一个未定义的错误。我称这个对象错了吗?我知道如何用画布绘制线条,我只是对如何从JSOn文件中这样做感到困惑。提前致谢。

1 个解决方案

#1


1  

Try wrapping the entire json file in brackets [], like this

尝试用括号[]包装整个json文件,就像这样

[{
    "line": {
        "width": 3,
        "stroke": "#FFFFFF",
        "x1": "640.386",
        "y1": "258.163",
        "x2": "816.364",
        "y2": "258.163"
    }   
}]

#1


1  

Try wrapping the entire json file in brackets [], like this

尝试用括号[]包装整个json文件,就像这样

[{
    "line": {
        "width": 3,
        "stroke": "#FFFFFF",
        "x1": "640.386",
        "y1": "258.163",
        "x2": "816.364",
        "y2": "258.163"
    }   
}]