簡體   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