calculate position of a point on image in percentage

允我心安 提交于 2019-12-11 11:41:00

问题


I am calculating position of a point on a image with the formula below in pixel, where oW is original image width and oH is original image height.

var x = oW * parseInt(document.getElementById('pageX').value - $tagImage.offset().left - 5) / $tagImage.width();

var y = oH * parseInt(document.getElementById('pageY').value - $tagImage.offset().top - 5) / $tagImage.height();

Now, I want to calculate same position in percentage so that the point remains responsive. (Sorry, I am a bit weak in maths so need help)


回答1:


Once you have the absolute offsets, you just divide by the total width or height (and multiply by 100 to get it as a percentage).

Here's an example, adapted from this answer.

$(".test").click(function(e){
  var offset = $(this).offset();
  alert('x = ' + ((e.pageX - offset.left) / $(this).outerWidth() * 100) + "%" );
  alert('y = ' + ((e.pageY - offset.top) / $(this).outerHeight() * 100) + "%" );
});
.test {
  width: 200px;
  height: 200px;
  background-color: green;
  margin-left: 50px;
  margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
  </div>
<div>


来源:https://stackoverflow.com/questions/35111425/calculate-position-of-a-point-on-image-in-percentage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!