Home > database >  Draw rectangles on canvas by reading JSON
Draw rectangles on canvas by reading JSON

Time:09-22

I'm trying to draw rectangles 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: If true, the rectangle filled without a border. If false the rectangle has a border but no filling.

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)
}
<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 which one of these methods are invoked. I would also suggest you convert the f property value to be a boolean, instead of a string.

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;

json.forEach(shape => {
  context[shape.f === 'true' ? 'fillRect' : 'strokeRect'](shape.x, shape.y, shape.w, shape.h);
});
<canvas id="c"></canvas>

  • Related