HLJ 发布于
2018-08-20 17:28:33

HTML5 Canvas获取鼠标位置坐标

为了获得相对于HTML5 Canvas的鼠标坐标,我们可以创建一个getMousePos()方法,该方法根据客户端鼠标的位置和从窗口对象的getBoundingClientRect()方法获得的画布的位置返回鼠标坐标。 说明:鼠标悬停在画布上以查看鼠标坐标

一个实例

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      function writeMessage(canvas, message) {
        var context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.font = '18pt Calibri';
        context.fillStyle = 'black';
        context.fillText(message, 10, 25);
      }
      function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
      }
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      canvas.addEventListener('mousemove', function(evt) {
        var mousePos = getMousePos(canvas, evt);
        var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
        writeMessage(canvas, message);
      }, false);
    </script>
  </body>
</html>
当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2018-08-20/184.html
最后生成于 2023-06-18 18:38:25
此内容有帮助 ?
0