你想往哪里走,在我的领域里你是跑不开我的指向的。

 使用JS实现鼠标指针特效

   效果图:

 

  代码如下,复制即可使用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>你想往哪里走</title>
</head>
<body>
<canvas id='canvas' width="500" height="500" style="background:#ccc;">
  你的浏览器不行啊~
</canvas>
<!--箭头函数-->
<script>
function Arrow() {
    this.x = 0; //初始位置
    this.y = 0;
    this.rotation = 0; //初始旋转角度
    this.color = '#ffff00';

}
//在原型上定义draw方法
Arrow.prototype.draw = function(context) {
    context.save();
    context.translate(this.x, this.y); //将坐标移到this.x 和 this.y
    context.rotate(this.rotation); //设置旋转角度
    context.lineWidth = 5; //设置线宽
    context.fillStyle = this.color; //设置填充色
    context.beginPath(); //路径开始
    context.moveTo(-50, -25);
    context.lineTo(0, -25);
    context.lineTo(0, -50);
    context.lineTo(50, 0);
    context.lineTo(0, 50);
    context.lineTo(0, 25);
    context.lineTo(-50, 25);
    context.closePath(); //路径闭合
    context.stroke(); //描边
    context.fill(); //填充
    context.restore();
}
</script> 
<!-- 工具函数 -->
<script>
//将utils定义为window对象下的一个属性,属性值为对象
window.utils = {};

//在utils对象上定义捕获坐标的方法
window.utils.captureMouse = function(element) {
    //定义一个名为mouse的对象
    var mouse = {
        x: 0,
        y: 0
    };

    //为元素绑定mousemove事件
    element.addEventListener('mousemove', function(event) {
        var x, y;

        //获取鼠标位于当前屏幕的位置, 并作兼容处理
        if (event.pageX || event.pageY) {
            x = event.pageX;
            y = event.pageY;
        } else {
            x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
        //将当前的坐标值减去元素的偏移位置,即为鼠标位于当前canvas的位置
        x -= element.offsetLeft;
        y -= element.offsetTop;

        mouse.x = x;
        mouse.y = y;
    }, false);
    //返回值为mouse对象
    return mouse;
}
</script> 
<script>
  window.onload = function(){
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var centerX = canvas.width/2;
    var centerY = canvas.height/2;
    
    //传入canvas,获取鼠标在canvas上移动是的坐标
    var mouse = utils.captureMouse(canvas);
         
    //新建一个arrow对象
    var arrow = new Arrow();
         
    //将arrow的坐标设置为canvas的中心
    arrow.x = centerX;
    arrow.y = centerY;
             
  //动画循环函数
  (function drawFrame(){
      window.requestAnimationFrame(drawFrame,canvas);
      context.clearRect(0, 0, canvas.width, canvas.height);
              
      //获取dy,dx值
      var dx = mouse.x - arrow.x,
      dy = mouse.y - arrow.y;
                  
      //设置旋转角度
      arrow.rotation = Math.atan2(dy, dx);
                
     //调用draw方法画出
      arrow.draw(context);

  })();
}

</script>
</body>
</html>

 如果你有更好的点子、想法,可以跟大家一起分享哦,如有错误,欢迎联系我指正,非常感谢!!!

原文地址:https://www.cnblogs.com/yidaixiaohui/p/8446982.html