如何使用鼠标动作围绕固定点旋转HTML画布对象? [英] How does one rotate a HTML canvas object around a fixed point using mouse action?

查看:138
本文介绍了如何使用鼠标动作围绕固定点旋转HTML画布对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,它可以用于手动调整时钟指针的应用。我想这可能涉及平移针(使针的终点旋转的中心),然后旋转它,然后平移针再次。



但是由于针头一直监听鼠标事件,因此会捕获第一个鼠标事件。结果是针最终被平移并且完全不旋转。鼠标事件不可能调试...



我可以参考的任何想法或代码片段?

解决方案

在您的示例中,您将需要计算时钟面(黑点)和当前鼠标位置(红点)相对于Y轴(如果你想象一个指南针,则是北北)。



我的trig正确,你可以使用下面的计算:

  var angle = Math.atan2(y2  -  y1,x2  - x1)* 180 / Math.PI; 

//将角度改为相对于Y轴而不是X
angle + = 90;
if(angle< 0){angle = 360 + angle; }

在公式中,x和y是两个点的坐标,知道(它是钟面的中心),另一个你可以从鼠标移动事件中获得。



一旦你有了角度,你可以简单地翻译

更新:我创建了一个jsfiddle来说明角度计算:



http:// jsfiddle。 net / DAEpy / 1 /




For example it may be used in the application of manually adjusting the hands of the clock. I guess it probably involves translating the needle (to make the end point of the needle the centre of rotation) then rotating it, then translating the needle again.

But since the needle listens to the mouse event all the time, the 1st mouse event will be captured. The result is that the needle ends up being translated and not rotated at all. Mouse event is impossible to debug too...

Any idea or code snippets that I can refer to? Using Javascript or CSS to rotate both fine.

解决方案

In your example, you will want to calculate the angle between the centre of the clock face (black dot), and the current mouse position (red dot), relative to the Y axis (cardinal north if you imagine a compass).

If I remember my trig correctly, you can calculate this by using the following:

var angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;

// alter the angle to be relative to Y axis instead of X
angle += 90;
if(angle < 0) { angle = 360 + angle; }

In the formula, x and y are the coordinates of the two points, one of which you will know (it is the centre of the clock face), and the other you can get from the mouse move event.

Once you have the angle, you can simply translate to the the centre of the circle, rotate the canvas by the calculated amount, and draw the hand.

Update: I created a jsfiddle to illustrate the angle calculation:

http://jsfiddle.net/DAEpy/1/

这篇关于如何使用鼠标动作围绕固定点旋转HTML画布对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆