how draw in canvas read a json?
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: 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"}
];