获取客户端边界矩形无国界(Get bounding client rectangle without

2019-10-21 08:31发布

我做了转换鼠标坐标到画布像素坐标的函数:

/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/
HTMLCanvasElement.prototype.relativeCoords = function(event) {
  var x,y;
  //This is the current screen rectangle of canvas
  var rect = this.getBoundingClientRect();

  //Recalculate mouse offsets to relative offsets
  x = event.clientX - rect.left;
  y = event.clientY - rect.top;
  //Also recalculate offsets of canvas is stretched
  var width = rect.right - rect.left;
  //I use this to reduce number of calculations for images that have normal size 
  if(this.width!=width) {
    var height = rect.bottom - rect.top;
    //changes coordinates by ratio
    x = x*(this.width/width);
    y = y*(this.height/height);
  } 
  //Return as an array
  return [x,y];
}

你可以看到的演示像素坐标计算 。 问题是,该解决方案的图像失败有border属性集 。

我怎样才能减去矩形边框的宽度? 性能件事呢 ,因为这种计算中鼠标移动事件经常进行。

Answer 1:

getComputedStyle包含你想要的信息:

在您的应用程序开始时一次撷取边界信息画布边界已定之后。

// get a reference to the canvas element
var canvas=document.getElementById('yourCanvasId');

// get its computed style
var styling=getComputedStyle(canvas,null);

// fetch the 4 border width values
var topBorder=styling.getPropertyValue('border-top-width');
var rightBorder=styling.getPropertyValue('border-right-width');
var bottomBorder=styling.getPropertyValue('border-bottom-width');
var leftBorder=styling.getPropertyValue('border-left-width');

如果这些范围的border-width变量的应用范围,您可以在HTMLCanvasElement.prototype.relativeCoords使用这些预取变量。

祝你的项目!



文章来源: Get bounding client rectangle without borders