html JS.Objects.Using Math.atan2使对象跟随鼠标指针

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html JS.Objects.Using Math.atan2使对象跟随鼠标指针相关的知识,希望对你有一定的参考价值。

canvas {
  border: 2px solid black;
}
var canvas, ctx, width, height;
var rect = {x:40, y:40, radius: 30, width:40, height:40, v:3};
var mousepos = {x:0, y:0};

function init() {
  canvas = document.querySelector("#myCanvas");
  ctx = canvas.getContext('2d');
  width = canvas.width;
  height = canvas.height; 
  
  canvas.addEventListener('mousemove', function (evt) {
        mousepos = getMousePos(canvas, evt);
     }, false); 
 
  mainloop();
}


function mainloop() {
    // 1) clear screen
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  
    // 2) move object
    var dx = rect.x - mousepos.x;
    var dy = rect.y - mousepos.y;
    var angle = Math.atan2(dy, dx);
  
    rect.x -= rect.v*Math.cos(angle);   
    rect.y -= rect.v*Math.sin(angle); 
  
    // 3) draw object
    drawRectangle(angle);
  
    // 4) request new frame
     window.requestAnimationFrame(mainloop);
}
 
function drawRectangle(angle) {
  ctx.save();
  
  // These two lines move the coordinate system
  ctx.translate(rect.x, rect.y);
  ctx.rotate(angle);
  // recenter the coordinate system in the middle
  // the rectangle. Like that it will rotate around
  // this point instead of top left corner
  ctx.translate(-rect.width/2, -rect.height/2);
  
  ctx.fillRect(0, 0, rect.width, rect.height);
  ctx.restore();
}

function getMousePos(canvas, evt) {
  // necessary to take into account CSS boudaries
  var rect = canvas.getBoundingClientRect();
  return {
     x: evt.clientX - rect.left,
     y: evt.clientY - rect.top
  };
}
JS.Objects.Using Math.atan2 to make an object follow the mouse pointer
----------------------------------------------------------------------


A [Pen](https://codepen.io/Onlyforbopi/pen/RYXEWW) by [Pan Doul](https://codepen.io/Onlyforbopi) on [CodePen](https://codepen.io).

[License](https://codepen.io/Onlyforbopi/pen/RYXEWW/license).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<title>Use Math.atan2 to make an object follow the mouse cursor</title>
</head>
<body onload="init();">
  <p>Move the mouse cursor and see the black rectangle following it.</p>
  <canvas id="myCanvas" width="400" height="400">
  </canvas>
</body>
</html>

以上是关于html JS.Objects.Using Math.atan2使对象跟随鼠标指针的主要内容,如果未能解决你的问题,请参考以下文章

Python读取mat文件

[MAT]使用MAT比較多个heap dump文件

Eclipse MAT插件下载地址

[Python] numpy.mat

python 笔记:读取mat文件

python读取.mat文件的数据