怎么画在画布上读一个json?

Bru*_*ise 6 html javascript json html5-canvas

我试图通过一个HTML5 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();
Run Code Online (Sandbox Code Playgroud)

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

[{"x":"247", "y":"373"}, {"x":"0", "y":"390"},{"x":"5", "y":"21"},{"x":"245", "y":"0"}, {"x":"247", "y":"373"}]
Run Code Online (Sandbox Code Playgroud)

Seb*_*mon 3

你所要做的就是循环遍历 JS 对象for并重复执行ctx.lineTo()。注意:ctx.lineTo()a 后面的第一个ctx.beginPath()字符的作用类似于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();
Run Code Online (Sandbox Code Playgroud)
<canvas id="yellow" width="250" height="400"></canvas>
Run Code Online (Sandbox Code Playgroud)

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

[
  {"x":"248", "y":"374"},
  {"x":"1",   "y":"391"},
  {"x":"6",   "y":"22" },
  {"x":"246", "y":"1"  },
  {"x":"248", "y":"374"}
];
Run Code Online (Sandbox Code Playgroud)