简体   繁体   中英

How to calculate the screen position using Javascript?

I have added label to a image and I need to determine the screen position of each label. Is it possible to get the screen position of each label? I have also uploaded the code maybe it might give an insight.

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';
};

You can use;

Element.getBoundingClientRect();

As stated in; https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

The returned value is a DOMRect object, which contains read-only left, top, right, bottom, x, y, width, height properties describing the border-box in pixels. Properties other than width and height are relative to the top-left of the viewport.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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