-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspring4.html
107 lines (100 loc) · 2.37 KB
/
spring4.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<style id="stylesheet">
.box {
position: absolute;
top: 10px;
left: 450px;
}
</style>
</head>
<body>
<div id="content">
<div class="point">
在canvas上移动鼠标试试:
</div>
<canvas id="canvas" width="400" height="300" style="background:#333"></canvas>
</div>
<script src="scripts/tool.js?id=1"></script>
<script id="scripts">
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var mouse = {
x: 0,
y: 0
};
var balles = []; //存放页面上的球
var spring = 0.03;
var friction = 0.95;
var gravity = 2;
var dx = 0;
var dy = 0;
// 球函数
function Ball(x, y, radius, speed) {
this.x = x;
this.y = y;
this.radius = radius;
this.angle = 0;
this.vx = 0;
this.vy = 0;
this.speed = speed;
};
//绘制球
function animation() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
balles.forEach(connect);
requestAnimationFrame(animation);
};
function drawBall(ball,targetX,targetY){
dx = targetX - ball.x;
dy = targetY - ball.y;
ctx.fillStyle = '#fff';
ctx.beginPath();
ball.vx += dx * spring;
ball.vy += dy * spring;
ball.vy += gravity;
ball.vx *= friction;
ball.vy *= friction;
ball.x += ball.vx;
ball.y += ball.vy;
ctx.arc(ball.x, ball.y, ball.radius, 0, 2 * Math.PI, true);
ctx.fill();
}
function connect(ball, i) {
if(i === 0) {
drawBall(ball,mouse.x,mouse.y);
ctx.moveTo(mouse.x, mouse.y);
} else {
var ballA = balles[i - 1];
drawBall(ball,ballA.x,ballA.y);
ctx.moveTo(ballA.x, ballA.y);
};
ctx.strokeStyle = '#fff';
ctx.lineTo(ball.x, ball.y);
ctx.stroke();
};
function mousedown(event) {
mouse.x = event.point.x;
mouse.y = event.point.y;
};
function mousemove(event) {
mouse.x = event.point.x;
mouse.y = event.point.y;
};
window.onload = function() {
for(var i = 0; i < 4; i++) {
var b = new Ball(10, 10, 10);
balles.push(b);
};
mouse.x = canvas.width/2;
animation();
tool.captureMT(canvas, mousedown, mousemove);
};
</script>
</body>
</html>