如何画在canvas读一个json?

how draw in canvas read a json?

我正在尝试在 HTML5 canvas 上画画。我设法利用 canvas 但我需要动态地进行。这是我的 JavaScript 代码:

var c=document.getElementById("yellow");
var ctx=c.getContext("2d");

ctx.beginPath();
ctx.moveTo(247,373);
ctx.lineTo(0,390);
ctx.lineTo(5,21);
ctx.lineTo(245,0);
ctx.lineTo(247,373);
ctx.closePath();
ctx.fillStyle="#ffca05";
ctx.globalAlpha=0.7;
ctx.strokeStyle = '#ffca05';
ctx.fill();
ctx.stroke();

我需要从这个 json array 中读取数据并使用这些坐标进行绘制。

[{"x":"247", "y":"373"}, {"x":"0", "y":"390"},{"x":"5", "y":"21"},{"x":"245", "y":"0"}, {"x":"247", "y":"373"}]

你所要做的就是在for循环中遍历JS对象并重复执行ctx.lineTo()。注意:ctx.beginPath() 之后的第一个 ctx.lineTo() 就像 ctx.moveTo().

您可以运行此代码片段来验证结果:

var c=document.getElementById("yellow");
var ctx=c.getContext("2d");
var json=[
  {"x":"247", "y":"373"},
  {"x":"0",   "y":"390"},
  {"x":"5",   "y":"21" },
  {"x":"245", "y":"0"  },
  {"x":"247", "y":"373"}
];

ctx.beginPath();
for(var i in json){
  ctx.lineTo(json[i].x,json[i].y);
}
ctx.closePath();
ctx.fillStyle="#ffca05";
ctx.globalAlpha=0.7;
ctx.strokeStyle="#ffca05";
ctx.fill();
ctx.stroke();
<canvas id="yellow" width="250" height="400"></canvas>

PS:我注意到 canvas 顶部边缘的顶角(大概还有左边那个)被切掉了一点。只需向每个坐标添加 1 左右即可解决此问题:

[
  {"x":"248", "y":"374"},
  {"x":"1",   "y":"391"},
  {"x":"6",   "y":"22" },
  {"x":"246", "y":"1"  },
  {"x":"248", "y":"374"}
];

我现在还不能发表评论,但是关于读取外部 JSON 文件的问题:如果您的文件在某些​​ URL 上可用,您可以通过 AJAX 使用 jQuery 轻松获取您需要的 JSON 数据,对其进行解析并将其存储在 webpage/application 的本地变量中。快速示例:

var myJSON; //the json object data you're going to draw to canvas with

$(document).ready(function(){
        $.ajax({
            url: "myurl.com/myjsonfile",
            dataType: "text",
            success: function(data) {
                myJSON = $.parseJSON(data);
                drawToCanvas(myJSON); //you can, perhaps, make the code
                                      //Xufox provided into a function that
                                      //you pass your myJSON var to once it
                                      //is loaded.
            }
        });
    })

'$.ajax' 调用将处理从上面指定的 URL 获取数据,并且仅在数据加载后才执行 'drawToCanvas()' 方法,并且传递给 myJSON(然后传递给方法)。

您可以直接在函数中引用参数,或将其存储在局部变量中:

function drawToCanvas(jsonObj) {
    var json = jsonObj;

    ctx.beginPath();
    for(var i in json){
       ctx.lineTo(json[i].x,json[i].y);
    }
    ...