如何在画布上绘制读取JSON? [英] how draw in canvas read a json?

查看:139
本文介绍了如何在画布上绘制读取JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制HTML5 canvas.我设法在画布上绘制,但我需要动态地进行绘制.这是我的JavaScript代码:

I'm trying to draw through on a HTML5 canvas. I managed to draw on the canvas but I need to do it dynamically. This is my JavaScript code:

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中读取数据并使用这些坐标进行绘制.

I need to read the data from this json array and draw using these coordinates.

[{"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().

All you have to do is iterate over the JS object in a for loop and repeatedly execute ctx.lineTo(). Note: the first ctx.lineTo() after a ctx.beginPath() acts like a ctx.moveTo().

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

You can run this code snippet to verify the result:

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:我注意到画布顶部边缘的上角(大概也是左边的角)被切除了.只需在每个坐标上添加1左右即可解决此问题:

PS: I can notice that the top corner at the top edge of the canvas (and presumably the left one as well) are a bit cut off. Just add 1 or so to each coordinate to fix this:

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

这篇关于如何在画布上绘制读取JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆