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

258
Visualizações
How to maintain position after changing div transform-origin?

Let's say I had the following code:

function rotate() {
  const elem = document.querySelector(".rect");

  elem.style.transformOrigin = "top right";
}
.rect {
  width: 200px;
  height: 100px;
  transform: rotateZ(45deg);
  background-color: #ddd;
  transform-origin: center;
}
<div class="rect"></div>

<button onclick="rotate()">Rotate</button>

You'll notice that when you click the Rotate button that the rectangle's transform-origin property changes from center to top right. As a result, the rectangle moves, because it is now rotated around a different origin.

Is it possible to have the rectangle maintain its current position, even after changing the transform origin? I am looking for a way to be able to change an element's transform origin while having it not move at all afterwards.

Basically, I'm looking for a way such that I can change the transform origin, but the div would be visually unchanged. I assume this involves some sort of translation in the rotate Javascript function, but I'm unsure of the exact calculations required to achieve such an effect.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The following seems to work:

function setRectangleOrigin(elem, newOrigin) {
  const compStyle = window.getComputedStyle(elem);

  const prevML = parseInt(compStyle.marginLeft);
  const prevMT = parseInt(compStyle.marginTop);

  const r1 = elem.getBoundingClientRect();
  elem.style.transformOrigin = newOrigin;
  const r2 = elem.getBoundingClientRect();

  elem.style.marginLeft = prevML + (r1.x - r2.x);
  elem.style.marginTop = prevMT + (r1.y - r2.y);
}

Call it like this:

setRectangleOrigin(document.querySelector(".elem"), "top left");

It takes the margin left and margin top of the current rectangle and then calculates its bounding client rect. It then applies the change to the transformation origin and then immediately gets the new bounding client rect.

Then it's a matter of simply transforming the margin left via the change in position.

about 4 years ago · Juan Pablo Isaza 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