繁体   English   中英

如何使用Javascript计算屏幕位置?

[英]How to calculate the screen position using Javascript?

我已经为图像添加了标签,我需要确定每个标签的屏幕位置。 是否可以获取每个标签的屏幕位置? 我也上传了代码,也许它可以提供一些见解。

function labelBox(Ncardinal, radius, domElement)
{
  this.screenVector = new THREE.Vector3(0, 0, 0);
  this.labelID = 'MovingLabel'+ Ncardinal.name;
  this.position = convertlatlonToVec3(Ncardinal.lat,Ncardinal.lon).multiplyScalar(radius);
  this.box = document.createElement('div');
  this.box.setAttribute("id", this.labelID);
  a = document.createElement('a');
  a.innerHTML = Ncardinal.name;
  a.href ='http://www.google.de';
  this.box.className = "spritelabel";
  this.box.appendChild(a);
  this.domElement = domElement;
  this.domElement.appendChild(this.box);
}

labelBox.prototype.update = function()
{
  this.screenVector.copy(this.position);  
  this.screenVector.project(camera);
  var posx = Math.round((this.screenVector.x + 1)* this.domElement.offsetWidth/2);
  var posy = Math.round((1 - this.screenVector.y)* this.domElement.offsetHeight/2);
  var boundingRect = this.box.getBoundingClientRect();
  //update the box overlays position
  this.box.style.left = (posx - boundingRect.width) + 'px';
  this.box.style.top = posy + 'px';
};

您可以使用;

Element.getBoundingClientRect();

如所述; https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

返回值是一个 DOMRect 对象,它包含只读的左、上、右、下、x、y、宽度、高度属性,以像素为单位描述边框。 宽度和高度以外的属性相对于视口的左上角。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM