有很多關於Stackoverflow的討論,關於如何在Canvas中獲取鼠標座標。我終於發現,在https://stackoverflow.com/a/5417934列出的解決方案很適合我,但有一個例外:畫布:當* border *存在時獲取鼠標座標
如果我把一個樣式定義爲畫布邊境進入我的文檔,即
<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]
}
當然,這是醜陋的。有沒有辦法在我的代碼中自動派生邊框大小?
使用getClientBoundingRect是要走的路:http://stackoverflow.com/questions/20060691/most-modern-method-of-getting-mouse-position-within-a-canvas-in-native-javascrip/20061533 #20061533 – GameAlchemist