两个箭头在圆圈内旋转

问题描述 投票:1回答:1

所以,我需要实现的基本思想是拥有一个从0到360度的简单圆。

在那个圆圈里面是两个箭头。我需要它们在圆圈内旋转。

一个箭头需要每度旋转度数,直到达到指定角度。另一个需要直接转向那个角度。

所以你的箭头都会从0度开始,如果你指定你想要达到100度,一个箭头会立即跳跃并指向100度,而另一个箭头会逐渐变为100度。

编辑:

抱歉,我对stackoverflow缺乏技巧(我刚才意识到我从来没有在我的问题中包含一个问题......)。所以我设法通过另一个关于stackoverflow的问题在画布中得到简单的箭头,但是当我开始研究实际旋转箭头时,我只是迷失在代码中。

我想我的问题是:如何根据用户选择的度数值将旋转应用于我的两个箭头?

所以这就是我设法制作箭头的方法:

<html>
<head>
</head>
<body>
<canvas id="c" width="500" height="500"></canvas>

<script langauage="javascript">
<!--
ctx = document.getElementById("c").getContext("2d");
ctx.beginPath();
canvas_arrow(ctx,50,50,100,50);
canvas_arrow(ctx,50,50,10,30);
ctx.stroke();


function canvas_arrow(context, fromx, fromy, tox, toy){
    var headlen = 10;   // length of head in pixels
    var dx = tox-fromx;
    var dy = toy-fromy;
    var angle = Math.atan2(dy,dx);
    context.moveTo(fromx, fromy);
    context.lineTo(tox, toy);
    context.lineTo(tox-headlen*Math.cos(angle-Math.PI/6),toy-headlen*Math.sin(angle-Math.PI/6));
    context.moveTo(tox, toy);
    context.lineTo(tox-headlen*Math.cos(angle+Math.PI/6),toy-headlen*Math.sin(angle+Math.PI/6));
}
-->
</script>
</body>
</head>

箭头很好,但让其中一个旋转而另一个跳转到所需的度数值是我觉得很难的。我找不到任何关于如何根据用户给出的度数值进行移动的示例或想法。

javascript jquery html5 canvas rotation
1个回答
1
投票

使用jQuery,你可以根据鼠标位置 - 你的元素获得度数,并应用CSS3变换rotate deg并设置动画过渡时间:

const $el = $('#circle'),
  $cir = $el.children();

$el.on('click', evt => {
  const o = $(evt.target).offset(),
    rad = $el.width() / 2,
    mPos = {
      x: evt.pageX - o.left,
      y: evt.pageY - o.top
    },
    a = Math.atan2(mPos.x - rad, mPos.y - rad),
    d = -a / (Math.PI / 180) + 180;

  $cir.css({transform: `rotate(${d}deg)`});
});
#circle {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  font-family: arial, helvetica, sans-serif;
  user-select: none; /* prevent text highlight */
  cursor: pointer;
}

#circle>* {
  text-align: center;
  position: absolute;
  border-radius: inherit;
  width: inherit;
  height: inherit;
}

#circle1 {
  background: #eee;
  transition: 1.3s;
}

#circle2 {
  background: #fff;
  transition: 0.3s;
  top: 20px;
  left: 20px;
  width: calc(150px - 40px);
  height: calc(150px - 40px);
}
<div id="circle">
  <div id="circle1">&#9660;</div>
  <div id="circle2">&#9650;</div>
</div>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.