会转弯的鼠标跟随效果

实现该效果主要用到两个知识点:

1、使用Math.atan2函数计算偏移角度

2、无限趋近的思想,主要是用到距离的无限趋近和角度的无限趋近

距离的无限趋近:

function lerpDis(t,c,r){
    	var delta = c-t;
    	return t + delta * r;
}

角度的无限趋近:

function lerpAngle(t,c,r){
    	var delta = c - t;
    	if(delta>Math.PI){
    		delta -= 2 * Math.PI;
    	}
    	if(delta<-Math.PI){
    		delta += 2 * Math.PI;
    	}
    	return t + delta * r;
}

示例代码:

var gs = (function(window,document,undefined){
	var canvas,ctx,w,h,x,y,mx,my,a;
	function init(){
		canvas = document.createElement("canvas");
		ctx = canvas.getContext("2d");
		w = window.innerWidth;
		h = window.innerHeight;
		canvas.width = w;
		canvas.height = h;
		document.body.appendChild(canvas);
		x = mx = w/2;
		y = my = h/2;
		a = 0;
		addEvent();
		draw();
	}
	function draw(){
		requestAnimationFrame(draw);
		ctx.clearRect(0,0,w,h);
		var angle = Math.atan2(my-y,mx-x) + Math.PI;
		a = lerpAngle(angle,a,0.7);
		x = lerpDistance(mx,x,0.93);
		y = lerpDistance(my,y,0.93);
		ctx.save();
		ctx.translate(x,y);
		ctx.rotate(a);
    	        ctx.beginPath();
    	        ctx.fillStyle = "#f00";
    	        ctx.arc(0,0,10,0,2*Math.PI,false);
    	        ctx.fill();
    	        ctx.beginPath();
    	        ctx.strokeStyle = "#f00";
    	        ctx.lineWidth = 5;
    	        ctx.lineCap = "round";
    	        ctx.moveTo(0,0);
    	        ctx.lineTo(100,0);
    	        ctx.stroke();
		ctx.restore();
	}
	function addEvent(){
		canvas.addEventListener("mousemove",mouseMove);
	}
	function mouseMove(){
		mx = event.offsetX == undefined ? event.layerX : event.offsetX;
		my = event.offsetY == undefined ? event.layerY : event.offsetY;
	}
	function lerpDistance(t,c,r){
		var delta = c - t;
		return t + delta * r;
	}
	function lerpAngle(t,c,r){
    	        var delta = c - t;
    	        if(delta>Math.PI){
    		      delta -= 2 * Math.PI;
    	        }
    	              if(delta<-Math.PI){
    		      delta += 2 * Math.PI;
    	       }
    	       return t + delta * r;
    }
    return { init : init };
})(window,document);

gs.init();

在线demo:http://demo.deanhan.cn/mouse-track

  • 支付宝二维码 支付宝
  • 微信二维码 微信
相关文章