DrakeJest
DrakeJest

Reputation: 187

How to draw squares inside a div element in javascript

I have a simple html div that will serve as like a viewport. and i need to draw 1 or more squares inside this div

<div style= "height: 400px; width: 400px; background-color: powderblue;"> </div>

I already can receive the dimension of the squares or rectangles. and upon receiving this data i must be able to draw squares that has no fill.

{x: 10, y: 20, height: 50, width: 50}
{x: 210, y: 120, height: 100, width: 70}

There can be 1 or more squares, and i must also be able to delete the drawn squares. But before all of that, how do i fist draw a square inside the div element just like the picture below? Squares that goes out of bounds of the div must be clipped

enter image description here

Upvotes: 0

Views: 685

Answers (2)

Joey Carlisle
Joey Carlisle

Reputation: 835

You can use the canvas api to draw shapes.

Make sure to set the size of the canvas element with css, and shapes should be clipped according to that size.

To delete a shape, simply delete the data, clear the canvas, and redraw.

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");

let rects = [
  {x: 10, y: 20, height: 50, width: 50},
  {x: 210, y: 120, height: 100, width: 70},
];

rects.forEach(r => {
  ctx.beginPath();
  ctx.rect(r.x, r.y, r.width, r.height);
  ctx.stroke();
});
<canvas id="canvas" />

Upvotes: 2

Radu Diță
Radu Diță

Reputation: 14211

You can set position: relative on the parent div and then use position: absolute and top, left, width and height for the children.

Something like this:

<div style= "height: 400px; width: 400px; background-color: powderblue;">
 <div style="position: absolute; left: 10px; top: 20px; height: 50px; width: 50px"></div>
</div>

You may need to add overflow: hidden on the parent and also add some borders on the children so they are visible.

Upvotes: 1

Related Questions