canvas获取鼠标位置

时间:2022-11-06 10:20:24

canvas获取鼠标位置

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        canvas{ border: 1px solid black; }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="500" height="500"></canvas>
    <script>
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");
        ctx.font = "16px Arial";

        canvas.addEventListener("mousemove", function(e) { 
            var cRect = canvas.getBoundingClientRect();              
            var canvasX = Math.round(e.clientX - cRect.left);        
            var canvasY = Math.round(e.clientY - cRect.top);         
            ctx.clearRect(0, 0, canvas.width, canvas.height);        
            ctx.fillText("X: "+canvasX+", Y: "+canvasY, 10, 20);
        });
    </script>
</body>
</html>