Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

200
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda