Google+中有一个特效:拖拽用户头像至分组内,用户头像会有一个特效(绕着圆圈转一圈)。写了个简单的示例,效果如下图所示:
核心部分就是:
for (var i = 0; i < 360; i+=1) {
var radius = Math.PI * i / 180;
//Math.cos(angle)、Math.sin(angle)
//todo….
}
1角度 = Math.PI / 180 => (π/180)
~ ~ 步长:
1:
2: //1度=π/180 弧度 ( ≈0.017453弧度 )
3:
4: !(function() {
5: for (var i = 0; i < 360; i+=1) {
6: var r = 200;
7: var x0 = 300;
8: var y0 = 300;
9:
10: var angle = Math.PI * i / 180;
11: var x = Math.cos(angle) * r + x0;
12: var y = Math.sin(angle) * r + y0;
13:
14: document.write(' ');
15:
16: r = 170;
17: x = Math.cos(angle) * r + x0;
18: y = Math.sin(angle) * r + y0;
19: document.write(' ');
20: }
21: })();
22:
23: function getEl(id) {
24: return typeof id === 'string' ? document.getElementById(id) : id;
25: }
26:
27: getEl("btn").onclick = moveHandler;
28:
29: function movePos(n) {
30: var el = getEl("modelEl");
31:
32: var r = 185;
33: var x0 = 300;
34: var y0 = 300;
35:
36: var angle = Math.PI * n / 180;
37: var x = Math.cos(angle) * r + x0 - el.offsetWidth/2;
38: var y = Math.sin(angle) * r + y0 - el.offsetHeight/2;
39:
40: el.style.left = x + 'px';
41: el.style.top = y + 'px';
42: }
43:
44: movePos(270);
45:
46: function transform(A) {
47: return 1 - Math.pow(1 - A, 3);
48: }
49:
50: function moveHandler() {
51: var base = 270;
52: var step = getEl('sel').value | 0;
53: var start = 360;
54: var end = 0;
55:
56: getEl("btn").disabled = true;
57:
58: var timer = setInterval(function() {
59: if (start >= end) {
60: movePos(base + start);
61: start -= step;
62:
63: step += transform((start - end)/360) / 100;
64: } else {
65: movePos(base + end);
66:
67: clearInterval(timer);
68:
69: if (moveHandler.count < 10) {
70: moveHandler.count++;
71:
72: setTimeout(function() {
73: getEl("sel").selectedIndex = Math.random() * getEl("sel").options.length | 0;
74:
75: moveHandler();
76: }, 100);
77: } else {
78: moveHandler.count = 0;
79: getEl("btn").disabled = false;
80: }
81:
82: }
83: }, 1);
84: }
85:
86: moveHandler.count = 0;
87:</ script > </ body > </ html >
本地运行示例:
~ ~开始运动 步长:1235810152030
预览代码