Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
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

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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" />

about 4 years ago · Santiago Gelvez Report

0

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.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!