調整大小(或滾動)後的滑鼠座標

Canvas 應用程式通常嚴重依賴使用者與滑鼠的互動,但是當調整視窗大小時,畫布所依賴的滑鼠事件座標可能會更改,因為調整大小會導致畫布在相對於視窗的不同位置偏移。因此,響應式設計要求在調整視窗大小時重新計算畫布偏移位置 - 並且還在滾動視窗時重新計算。

此程式碼偵聽視窗大小調整事件並重新計算滑鼠事件處理程式中使用的偏移量:

// variables holding the current canvas offset position
//    relative to the window
var offsetX,offsetY;

// a function to recalculate the canvas offsets
function reOffset(){
    var BB=canvas.getBoundingClientRect();
    offsetX=BB.left;
    offsetY=BB.top;        
}

// listen for window resizing (and scrolling) events
//     and then recalculate the canvas offsets
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }

// example usage of the offsets in a mouse handler
function handleMouseUp(e){
    // use offsetX & offsetY to get the correct mouse position
    mouseX=parseInt(e.clientX-offsetX);
    mouseY=parseInt(e.clientY-offsetY);
    // ...
}