檢測畫布上的滑鼠位置
此示例將顯示如何獲取相對於畫布的滑鼠位置,以便 (0,0) 將成為 HTML5 Canvas 的左上角。e.clientX 和 e.clientY 將獲得相對於文件頂部的滑鼠位置,將其更改為基於畫布的頂部我們從客戶端 X 和 Y 中減去畫布的 left 和 right 位置。
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "16px Arial";
canvas.addEventListener("mousemove", function(e) {
var cRect = canvas.getBoundingClientRect(); // Gets CSS pos, and width/height
var canvasX = Math.round(e.clientX - cRect.left); // Subtract the 'left' of the canvas
var canvasY = Math.round(e.clientY - cRect.top); // from the X/Y positions to make
ctx.clearRect(0, 0, canvas.width, canvas.height); // (0,0) the top left of the canvas
ctx.fillText("X: "+canvasX+", Y: "+canvasY, 10, 20);
});
Math.round 的使用是由於確保 x,y 位置是整數,因為畫布的邊界矩形可能沒有整數位置。