Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda