在没有jQuery的画布中获取光标位置 [英] Getting cursor position in a canvas without jQuery

查看:136
本文介绍了在没有jQuery的画布中获取光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习如何使用HTML canvas元素,当然,我正在制作一个绘图应用程序。所以,我有代码设置为实际绘图和动画部分的应用程序,但我不知道如何获得鼠标光标的位置。我真的不喜欢不使用jQuery,因为我宁愿不想学习它所做的一切,并必须经历它的设置过程。感谢您的帮助!

I am trying to learn how to use the HTML canvas element, and naturally, I am making a drawing application. So, I have the code set up for the actual drawing and animating part of the app, but I am not sure how to approach getting the position of the mouse cursor. I really would prefer not to use jQuery, for I would rather not want to learn all of what it does and have to go through the process of getting it set up. Thanks for any help!

推荐答案

  function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect(), root = document.documentElement;

    // return relative mouse position
    var mouseX = evt.clientX - rect.left - root.scrollLeft;
    var mouseY = evt.clientY - rect.top - root.scrollTop;
    return {
      x: mouseX,
      y: mouseY
    };
  }

  window.onload = function() {
    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;
      alert(message);
    }, false);
  };

来源

这篇关于在没有jQuery的画布中获取光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆