【问题标题】:Get bounding client rectangle without borders获取没有边框的边界客户矩形
【发布时间】:2014-11-29 15:58:29
【问题描述】:

我做了一个将鼠标坐标转换为画布像素坐标的函数:

/* 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];
}

您可以看到pixel coordinate calculation 的演示。问题是图像having border property set的解决方案失败。

如何从矩形中减去边框宽度?性能确实很重要,因为此计算通常在鼠标移动事件期间执行。

【问题讨论】:

标签: javascript html5-canvas coordinates dom-events


【解决方案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');

如果您将这些边框宽度变量限定在应用程序范围内,则可以在 HTMLCanvasElement.prototype.relativeCoords 中使用这些预取变量。

祝你的项目好运!

【讨论】:

  • 我不确定所有计算样式的获取和整数解析速度如何,但it definitelly works,即使对于各种奇怪的边框尺寸(ptem...) .
  • @TomášZato gCS 始终以像素为单位进行计算,事实上,浏览器中的所有内容最终都以像素为单位,因为这是屏幕能够理解的唯一单位。因此,当使用任意单位(例如 pt、em 等)时,这些单位会在内部转换为像素,然后再显示任何内容,这在您请求维度时再次成为 gCS 的基础。
  • @TomášZato 顺便说一句,您还需要这个来填充。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
相关资源
最近更新 更多