如何使用getBoundingClientRect()编辑图像的“ hitbox”;

时间:2019-04-25 14:42:49

标签: javascript html image

我有一幅图像漂浮在页面上,我需要制作图像,以便当它碰到某物时发生某些事情。在执行此操作时,我使用了getBoundingClientRect();。为了找到图像的位置,找到它命中时。令人讨厌的是,图像的位置与在线显示的位置相差约100 px(不精确)。我该如何解决?

我已经尝试过更改图像的此高度/宽度元素,但没有用。

 <!dOcTyPe HtMl>
 <meta name="viewport" content="width=device-width, initial- 
 scale=1">
 <style>
 span{
    height: 25px;
    width: 25px;
    border-radius: 13px;
    background-color: white;
    display: inline-block;
    position: fixed;
    }
   #myDiv{
    max-width: 100px;
    }
    #eve{
    margin-top: 0px;
    margin-left: 0px;
    background-color: white;
    height: 300px;
    border-radius: 25px;
    border: 3px gray solid;
    }
    .body{
    background-color: black;
    }
     .circimg{
    height: 25px;
    width: 25px;
    background: none;

    }
    #dot{
    position: absolute;
    top: 50px;
    }
    </style>
  <body class="body">
  <audio id="audio" 
  src="http://www.willmargulies.com/gimn_rf_t3- 
   [AudioTrimmer.com].mp3" autoplay="false" ></audio>
   <img id="dot" class="circimg" top="0px" 
   src="https://www.willmargulies.com/PinClipart.com_label- 
   clipart_183729.png">
    <script>
   function playSound() {
      var sound = document.getElementById("audio");
      sound.play();
      }
    </script>
  <script>
    document.getElementsByTagName("img").top = "50px";

  var div = document.getElementById("dot");
  var x = 0
  var lr = 1;
  var concise = 1;
  var y = 0;
  var he = window.innerWidth - 50;
  var inwit = window.innerWidth - 30;
  var inhei = window.innerHeight - 15;
   function func(){

  div.style.top = y + "px";     
  div.style.left = x + "px"; 

  if(div.style.left === he + "px"){lr = 0;}
  if(div.style.left === "20px"){lr = 1;}
  if(lr === 1){x = x + 1}else{x = x - 1}

  if(div.style.top === inhei + "px"){concise = 0;}
  if(div.style.top === "15px"){concise = 1;}
  if(concise === 1){y = y + 1}
  else{y = y - 1}

  if(div.style.left === "0" && div.style.top === "0px"){
  playSound();
  }



  var span1 = document.getElementById("dot");
  var button = document.getElementById("eve");

  var rect1 = span1.getBoundingClientRect();
  var rect2 = button.getBoundingClientRect();

  var overlap = (rect1.right == rect2.left ||  
  rect1.left == rect2.right ||                
  rect1.bottom == rect2.top ||                 
  rect1.top == rect2.bottom)                  

  if(overlap){
  alert("holy bjesus")
  }

        }



   setInterval(func, 5);

  </script>
  <center>
     <button id="eve" class="" onClick="if(touches(span, btn))                                    
   {alert('k');}">Putin The Bootin</button>
  </center></body>

0 个答案:

没有答案