【问题标题】:how do i rotate a rectangle to point towards mouse我如何旋转一个矩形指向鼠标
【发布时间】:2016-08-08 02:36:15
【问题描述】:

每次鼠标移动时,我都需要帮助旋转一个矩形以指向屏幕上的鼠标。我一直在尝试使用 onmousemove 事件并计算度数/角度,然后转换为弧度,但由于某种原因,当我将弧度变量 rad 放在 rotate(); 中时,矩形根本不旋转。

<!DOCTYPE html>
<html>
<head>
<title>Rotate Rectangle Project</title>
<style>
canvas {
background:#f05424; display: block; margin: 0 auto;
}
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>

<canvas id="myCanvas" width=500 height=500 top=10px></canvas>
<p id='coord'>0</p>
<p id='degree'>0</p>
<p id='radian'>0</p>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");




var x = 100;
var y = 100;
var w = 100;
var h = 30;
var rX, rY, mX, mY, degrees, rad, coords;

document.onmousemove = function(e){
rX =533;
rY =100;

mX = e.clientX;
mY = e.clientY;

coords = mX + ',' + mY;
degrees = mY - rY + mX - rX;


rad = Math.atan2(mY - rY, mX - rX)* Math.PI/180;
draw();

document.getElementById('coord').innerHTML = coords;
document.getElementById('degree').innerHTML = degrees;
document.getElementById('radian').innerHTML = rad;
};



function rectangle(){

ctx.beginPath();
ctx.translate(x, y);
ctx.rotate(rad);
ctx.translate(-x, -y);
ctx.rect(x, y, w, h);
ctx.fillStyle = '#f8c778';
ctx.fill();
ctx.closePath();


}
function draw(){
ctx.clearRect(x,y,canvas.width,canvas.height);
rectangle();
}









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

【问题讨论】:

  • 您需要在onmousemove中致电rectangle
  • 啊,谢谢,我很感激,我对编程有点陌生,哈哈。

标签: javascript rotation mouse atan2


【解决方案1】:

我已经编辑了你的代码,基本上你需要在onmousemove上调用rectangle并清除画布。

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");
var x = 100;
var y = 100;
var w = 100;
var h = 30;
var mouseX, mouseY, degrees, rad, coords;

document.onmousemove = function(e) {
  mouseX = e.clientX;
  mouseY = e.clientY;
  coords = mouseX + ',' + mouseY;
  degrees = mouseY - y + mouseX - x;
  rad = Math.atan2(mouseY - y, mouseX - x) * (180 / Math.PI);
  rectangle();
};



function rectangle() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.translate(x, y);
  ctx.rotate(rad);
  ctx.translate(-x, -y);
  ctx.rect(x, y, w, h);
  ctx.fillStyle = '#f8c778';
  ctx.fill();
  ctx.closePath();
}
body {
  margin: 0px;
  padding: 0px;
}

canvas {
  background: #f05424;
  display: block;
  margin: 0 auto;
}
&lt;canvas id="myCanvas" width=500 height=500&gt;&lt;/canvas&gt;

【讨论】:

  • 有趣,我已经将它应用到我的代码中,我意识到矩形无法控制地旋转。当通过 onmousemove 事件找到弧度时,矩形不应该指向鼠标线吗?我更新了我的代码并更改了各种变量,希望能解决让矩形指向鼠标线的问题,但到目前为止没有任何效果......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 2012-03-01
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 2018-12-06
  • 2013-04-14
相关资源
最近更新 更多