以百分比计算图像上点的位置 [英] calculate position of a point on image in percentage

查看:312
本文介绍了以百分比计算图像上点的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下公式(以像素为单位)计算图像上点的位置,其中oW是原始图像宽度,oH是原始图像高度.

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)

推荐答案

一旦有了绝对偏移量,就将其除以宽度或高度的总和(乘以100即可得到百分比).

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>

这篇关于以百分比计算图像上点的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆