在 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/