作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试在 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/
我是一名优秀的程序员,十分优秀!