其他分享
首页 > 其他分享> > canvas获取鼠标位置

canvas获取鼠标位置

作者:互联网

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>

标签:canvas,鼠标,ctx,cRect,获取,canvasY,var,Math
来源: https://www.cnblogs.com/ye-hcj/p/10356376.html