javascript - 圆跟随鼠标 HTML5 Canvas jQuery

标签 javascript html html5-canvas

我正在尝试在我在游戏中使用的 HTML Canvas 中制作一个跟随鼠标的圆圈。我试图让圆圈每次迭代移动 5px,但水平移动时速度较慢,垂直移动时速度较快。这是我使用的数学:

x=distance between mouse and circle on the x-axis
y=distance between mouse and circle on the y-axis
z=shortest distance between mouse and circle
a=number of units circle should move along the x-axis
b=number of units circle should move along the y axis


x^2 + y^2=z^2
Want the total distance traveled every iteration to be five pixels
a^2 + b^2 = 25
b/a=y/x
b=ay/x
a=sqrt(25-ay/x^2)
a^2+ay/x-25=0
Use Quadratic formula to find both answers
a=(-y/x+-sqrt(y/x)^2+100)/2

我在下面的代码中复制了这个问题

$(function(){
      let canvas = $("canvas")[0];
      let ctx = canvas.getContext("2d");
      
      //Gets position of mouse and stores the value in variables mouseX and mouseY
      let mouseX = mouseY = 0;
      $("canvas").mousemove(function(e){
        mouseX = e.pageX;
        mouseY = e.pageY;
      }).trigger("mousemove");

      let circleX = 0;
      let circleY = 0;
      function loop(t){
        //Background
        ctx.fillStyle="blue";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        let xFromMouse = mouseX-circleX;
        let yFromMouse = mouseY-circleY;
        let yxRatio = yFromMouse/xFromMouse;
        let xyRatio = xFromMouse/yFromMouse;
        let speed = 25;
        let possibleXValues = [(-yxRatio+Math.sqrt(Math.pow(yxRatio,2)+(4*speed)))/2,(-yxRatio-Math.sqrt(Math.pow(yxRatio,2)+(4*speed)))/2];
        
        //I use this code as a temporary fix to stop the circle from completely disappearing
        if(xFromMouse === 0 || isNaN(yxRatio) || isNaN(possibleXValues[0]) || isNaN(possibleXValues[1])){
          possibleXValues = [0,0];
          yxRatio = 0;
        }
        //Uses b=ay/x to calculate for y values
        let possibleYValues = [possibleXValues[0]*yxRatio,possibleXValues[1]*yxRatio];

        if(xFromMouse >= 0){
          circleX += possibleXValues[0];
          circleY += possibleYValues[0];
        } else {
          circleX += possibleXValues[1];
          circleY += possibleYValues[1];
        }
        
        ctx.beginPath();
        ctx.arc(circleX, circleY, 25, 0, 2 * Math.PI,false);
        ctx.fillStyle = "red";
        ctx.lineWidth = 0;
        ctx.fill();

        window.requestAnimationFrame(loop);
      }
      window.requestAnimationFrame(loop);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas width="450" height="250"></canvas>

最佳答案

我认为使用笛卡尔到极坐标转换可能会更好。这是我之前做的一个例子。这将使您能够在每次迭代“速度”上保持一致的步骤。

//Canvas, context, mouse.
    let c, a, m = { x:0, y:0};
    
    //onload.
    window.onload = function(){
    	let circle = {},
    		w, h,
    		speed = 5; //step speed = 5 "pixels" (this will be fractional in any one direction depending on direction of travel).
    
        //setup
    	c = document.getElementById('canvas');
    	a = c.getContext('2d');				
    	w = c.width = window.innerWidth;
    	h = c.height = window.innerHeight;
    	
    	function move(){
    		//get distance and angle from mouse to circle.
            let v1m = circle.x - m.x,
    			v2m = circle.y - m.y,
    			vDm = Math.sqrt(v1m*v1m + v2m*v2m),
    			vAm = Math.atan2(v2m, v1m);
    			
    			//if distance is above some threshold, to stop jittering, move the circle by 'speed' towards mouse.
                if(vDm > speed) { 
    				circle.x -= Math.cos(vAm) * speed;
    				circle.y -= Math.sin(vAm) * speed;
    			}
    	}
    	
    	function draw(){
    		//draw it all.
            a.fillStyle = "blue";
    		a.fillRect(0,0,w,h);
    
    		a.fillStyle = "red";
    		a.beginPath();
    			a.arc(circle.x, circle.y, circle.r, Math.PI * 2, false);
    		a.closePath();
    		a.fill();
    	}
    	
    	circle = {x:w/2, y:h/2, r:25};
    	
    	function animate(){
    		requestAnimationFrame(animate);
    		move();
    		draw();
    	}
    
    	c.onmousemove = function(e){
    		m.x = e.pageX;
    		m.y = e.pageY;
    	};
    
    	animate();
    }
<canvas id="canvas" width="450" height="250"></canvas>

关于javascript - 圆跟随鼠标 HTML5 Canvas jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54278218/

相关文章:

javascript - 为什么我不能在我的 HTML5 canvas 中绘制一个矩形?

javascript - JS 客户端 Exif 方向 : Rotate and Mirror JPEG Images

javascript - For循环变量自动递增

javascript - .otherwise 或/** 在新的 Angular2 Router 中通过通配符路由非路由

javascript - Sproutcore 自定义 CSS

javascript - Angular ng-repeat 不重复 tr

javascript - 无法创建动态 div 以在单击和返回时更改大小

javascript - 我可以访问 HTML 5 中的图像对象吗?

javascript - 由于 JavaScript 的限制,Vue 无法检测数组的更改。有什么限制?

java - 如何确保 A href 的绝对 URL 重定向