首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >圆圈跟随鼠标HTML5画布jQuery

圆圈跟随鼠标HTML5画布jQuery
EN

Stack Overflow用户
提问于 2019-01-20 23:56:16
回答 1查看 374关注 0票数 0

我正试着在游戏中使用的HTML画布上跟着鼠标画一个圆圈。我试图让圆在每次迭代中移动5px,但它在水平移动时速度较慢,垂直移动时速度较快。下面是我使用的数学公式:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
$(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);
    });
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas width="450" height="250"></canvas>

EN

Stack Overflow用户

回答已采纳

发布于 2019-01-21 09:44:46

我认为你最好使用笛卡尔到极坐标的转换。这是我之前做的一个例子。这将允许你在每次迭代中都有一个一致的步长“速度”。

代码语言:javascript
复制
//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();
    }
代码语言:javascript
复制
<canvas id="canvas" width="450" height="250"></canvas>

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54278218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档