Search code examples
javascripthtmlcssimageposition

Adapt image movement to window size in javascript


I made an animation on my website which moves if clicked on. The problem is that on the javascript function that manage it, I gave a series of coordinates which fits only if the browser is in full screen. Here are some example: https://i.sstatic.net/wTJnG.jpg and https://i.sstatic.net/f9Bg2.jpg This is my javascript function:

function init(){
   imgObj = document.getElementById('minion');
   immagine = document.getElementById('immagine_minion');
   imgObj.style.position= 'absolute'; 
   imgObj.style.top = '240px';
   imgObj.style.left = '-300px';
   imgObj.style.visibility='hidden';
   appaer();
 }


And this, for example, the method which moves it as soon as I open the page:

function appaer(){
  immagine.src="../img/minion_dx.png";
  if (parseInt(imgObj.style.left)<200) {
   imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px';
   imgObj.style.visibility='visible';
   animate = setTimeout(appaer,20);
 } else 
 stop();
}

How can I make it fit for every screen resolution?


Solution

  • this should get you started

    var stage_number = 0
    
    function go_to_next_stage() {
      stage_number++
      var stage = document.getElementById("stage" + stage_number)
      me.style.left = getComputedStyle(stage).getPropertyValue("left")
      me.style.top = getComputedStyle(stage).getPropertyValue("top")
      if (stage_number > 3) stage_number = 0
    }
    img {
      position: absolute;
      left: -100px;
      top: 0;
      transition: left 2s, top 2s
    }
    
    .stage {
      width: 100px;
      height: 100px;
      border: 1px solid black;
      position: absolute;
    }
    
    #stage1 {
      left: 0;
      top: 0;
    }
    
    #stage2 {
      right: 0;
      top: 0;
    }
    
    #stage3 {
      right: 0;
      bottom: 0;
    }
    
    #stage4 {
      left: 0;
      bottom: 0;
    }
    
    div {
      width: 100vw;
      height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    <img id="me" src="https://de.gravatar.com/userimage/95932142/195b7f5651ad2d4662c3c0e0dccd003b.png?size=100" />
    <div onclick="go_to_next_stage()">click anywhere to continue</div>
    
    <div class="stage" id="stage1">
    </div>
    <div class="stage" id="stage2">
    </div>
    <div class="stage" id="stage3">
    </div>
    <div class="stage" id="stage4">
    </div>