javascript - 当 *border* 存在时 Canvas : Get Mouse Coordinates,

标签 javascript css html5-canvas

在 Stackoverflow 上有很多关于如何在 Canvas 中获取鼠标坐标的讨论。我终于找到了 https://stackoverflow.com/a/5417934 中概述的解决方案对我来说效果很好,但有一个异常(exception):

如果我将 Canvas 边框的样式定义放入我的文档中,即

<style>
  canvas { border: 42px solid red; }
</style>

我得到的鼠标位置恰好偏离了边框大小(我可以通过调整边框大小轻松验证这一点)。作为临时解决方案,我通过边框大小手动调整鼠标坐标,最后得到以下获取鼠标坐标的函数:

function getCursorPosition1(event) { 
  var canoffset=$('#pinaka').offset(); // Id of canvas is 'pinaka'
  var x=event.clientX+document.body.scrollLeft+document.documentElement.scrollLeft-Math.floor(canoffset.left) - 42;
  var y=event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor(canoffset.top) + 1 - 42;
  return [x,y]
}

当然这很丑陋。有没有办法在我的代码中自动导出边框大小?

最佳答案

您可以使用 window.getComputedStyle 获取边框宽度。

<canvas id="canvas"></canvas>

var canvas = document.getElementById("canvas");
var computedStyle = window.getComputedStyle(canvas,null);
var topBorder=computedStyle.getPropertyValue("border-top-width");
var leftBorder=computedStyle.getPropertyValue("border-left-width");
var bottomBorder=computedStyle.getPropertyValue("border-bottom-width");
var rightBorder=computedStyle.getPropertyValue("border-right-width");

(需要 IE9+)

关于javascript - 当 *border* 存在时 Canvas : Get Mouse Coordinates,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20516119/

相关文章:

javascript - 当屏幕尺寸变化时如何获取图像宽度?

html - CSS 动画播放不正确 - 断断续续?

javascript - 如何从javascript函数中获取值?

javascript - 使用 Pixi.js/html Canvas 绘制鼠标选择区域(橡皮筋)

javascript - 使 postMessage() 和 addEventListener() 与 IE8 兼容

javascript - 如何用href定位div加载

javascript - 如何导出对数据库连接的引用?

javascript - 绝对定位的 DIV 不可见

html - Shiny 的选择下拉菜单向上打开

javascript - Html2Canvas 截图清晰度