How to place the transfom origin point of element in center of the view port

288 Views Asked by At

I'm trying to make a website where you can zoom and pan. Currently I'm working with the panzoom package, but the user should be able to rotate the scene content around the center of their screen.

I know how the transform-origin property works but I can't seem to figure out how to change it relative to the view port.

example

Here is a JSFiddle I'm working on: https://jsfiddle.net/jsrhkom4/28/.

HTML

<div class="scene">
  <div class="scene__content">
    <img src="https://picsum.photos/id/237/500/500">
    <img src="https://picsum.photos/id/237/500/500">
    <img src="https://picsum.photos/id/237/500/500">
    <img src="https://picsum.photos/id/237/500/500">
  </div>
</div>

<div class="bar">
  <div class="js-turn-left">Rotate left</div>
  <div class="js-turn-right">Rotate right</div>
</div>

CSS

.scene__content {
  transition: transform 1s ease-in-out;
  max-width: fit-content;
  max-height: fit-content;
  
  display:grid;
  grid-template-columns: 200px 200px;
  grid-row: auto auto;
  grid-column-gap: 20px;
  grid-row-gap: 20px;
  
  img {
    width: 100%;
    
    &:nth-child(1) {
      transform: rotate(180deg);
    }
    
    &:nth-child(2) {
      transform: rotate(270deg);
    }
    
    &:nth-child(3) {
      transform: rotate(90deg);
    }
  }
}

.bar {
  position: fixed;
  z-index: 9;
  bottom:0;
  left:0;
  right:0;
  padding: 15px 0;
  background-color:red;
  display:flex;
  justify-content: space-around;
  align-items:center;
  
  div {
    padding: 15px 30px;
    background-color: crimson;
    cursor: pointer;
  }
}

JS

const el = document.querySelector('.scene');
const scene = panzoom(el, {
  maxZoom: 1.5,
  minZoom: 0.5,
  smoothScroll: true,
  bounds: true
});

const turnLeft = document.querySelector('.js-turn-left');
const turnRight = document.querySelector('.js-turn-right');
const content = document.querySelector('.scene__content');
let angle = 0;

turnLeft.addEventListener('click', () => {
    angle-=45;
    content.style.transform = "rotate(" + angle + "deg)";
});
turnRight.addEventListener('click', () => {
    angle+=45;
    content.style.transform = "rotate(" + angle + "deg)";
});

Demo: https://jsfiddle.net/jsrhkom4/28/show.

Thanks in advance!

0

There are 0 best solutions below