Home > front end >  draw on canvas by reading json
draw on canvas by reading json

Time:09-22

I'm trying to draw through on a HTML5 canvas. I managed to draw on the canvas but I need to do it dynamically.

x,y: coordinates of the position of the rectangle in the canvas-element.
w: width of the rectangle.
h: height of the rectangle.
f: true:Rectangle is filled without a border, false: rectangle has a border but no filling.

This is my JavaScript code:

var canvas = document.getElementById("c");
    var context = canvas.getContext("2d");
    var json=[
        {"x":"50", "y":"50", "w":"100", "h":"50", "f":"true"},
        {"x":"50", "y":"150", "w":"100", "h":"50", "f":"false"}
    ];

    context.beginPath();
    for(var i in json){
        context.lineTo(json[i].x, json[i].y, json[i].w, json[i].h, json[i].f)
    }

CodePudding user response:

Since your' json has a x, y, width and height, but lineTo expects coordination points, we'll need to sum the width with x, same for height y

var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
var json=[
    {"x":"50", "y":"50", "w":"100", "h":"50", "f":"true"},
    {"x":"50", "y":"100", "w":"100", "h":"50", "f":"false"}
];

context.beginPath();

for(var i in json){
  const { x, y, w, h, f } = json[i];
  
  context.moveTo(x, y);
  context.lineTo(x   w, y   h);
  context.stroke();
}
<canvas id='c'></canvas>

CodePudding user response:

As you're attempting to draw rectangles on your canvas, it would make far more sense to use the strokeRect() and fillRect() methods.

Note that your f property will determine whether one or both of these methods are invoked.

var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
var json = [{
    "x": "50",
    "y": "50",
    "w": "100",
    "h": "50",
    "f": "true"
  },
  {
    "x": "50",
    "y": "150",
    "w": "100",
    "h": "50",
    "f": "false"
  }
];

context.canvas.width = 200;
context.canvas.height = 250;

for (var i in json) {
  context.strokeRect(json[i].x, json[i].y, json[i].w, json[i].h);
  if (json[i].f === 'true')
    context.fillRect(json[i].x, json[i].y, json[i].w, json[i].h);
}
<canvas id="c"></canvas>

  • Related