javascript - 如何在 Canvas 中绘制读取 json?

标签 javascript html json html5-canvas

我正在尝试在 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 数组 中读取数据并使用这些坐标进行绘制。

[{"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 顶部边缘的顶 Angular (大概还有左边的那个)被切掉了一点。只需向每个坐标添加 1 左右即可解决此问题:

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

关于javascript - 如何在 Canvas 中绘制读取 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29904750/

相关文章:

html - 导航栏上的下拉问题

html - 如何在这些表单框之间填充一些内容?

c# - 在 JSON.NET 中如何获取对每个反序列化对象的引用?

mysql - 如何从 mysql 数据库创建 json 文件?

java - 当JSON文件没有任何且只有获取对象时如何创建数组

javascript - JS : Counting Elements in Array -> Returning Array of Arrays

javascript - 如何在 Remix.run 开发模式下使用内存缓存?

javascript - 提交 HTML 表单以在新页面中显示输入的信息

html - JSP 不获取 bootstrap css (IDEA + Tomcat)

javascript - 使用 JQuery、Ajax 和 PHP 的登录处理程序