-
Notifications
You must be signed in to change notification settings - Fork 0
/
c07.html
143 lines (106 loc) · 2.85 KB
/
c07.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<style>
body {
background: #dddddd;
}
#canvas {
background: #ffffff;
border: thin inset #aaaaaa;
}
</style>
</head>
<body>
<canvas id='canvas' width="800" height="600">
Canvas not supported
</canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
function windowToCanvas(x, y) {
var bbox = canvas.getBoundingClientRect();
return { x : x - bbox.left, y : y - bbox.top }
}
function Vector2d(x, y) {
this.x = x;
this.y = y;
}
Vector2d.prototype = {
add : function (vec) {
return new Vector2d(this.x + vec.x, this.y + vec.y);
},
sub : function (vec) {
return new Vector2d(this.x - vec.x, this.y - vec.y);
},
scale : function (scale) {
return new Vector2d(this.x * scale, this.y * scale);
},
length : function () {
return Math.sqrt(this.x * this.x + this.y * this.y);
},
normalize : function () {
var len = this.length();
return new Vector2d(this.x / len, this.y / len);
},
perp : function (cw) {
if(cw)
return new Vector2d(-this.y , this.x);
else return new Vector2d( this.y, -this.x);
},
dot : function (vec) {
return this.x * vec.x + this.y * vec.y;
}
};
function Ball() {
this.x = 0;
this.y = 0;
this.radius = 10;
this.color = "red";
this.angle = 0;
}
Ball.prototype = {
draw : function() {
context.save();
context.beginPath();
context.translate(this.x, this.y);
context.rotate(this.angle);
context.arc(0, 0, this.radius, 0, Math.PI * 2);
context.fillRect(-30, -5, 30, 10);
context.fillStyle = this.color;
context.fill();
context.restore();
}
}
var ball = new Ball();
var vx = 0;
var vy = 0;
var speed = 5;
ball.x = 100;
ball.y = 500;
//ball.angle = 45 * Math.PI / 180;
canvas.onmousemove = function(e) {
var loc = windowToCanvas(e.clientX, e.clientY);
var dx = loc.x - ball.x;
var dy = loc.y - ball.y;
var m = new Vector2d(dx, dy);
m = m.normalize().scale(speed);
vx = m.x;
vy = m.y;
};
requestAnimationFrame(loop);
function loop() {
context.clearRect(0, 0, canvas.width, canvas.height);
ball.angle = Math.atan2(vy, vx);
ball.x += vx;
ball.y += vy;
render();
requestAnimationFrame(loop);
}
function render() {
ball.draw();
}
</script>
</body>
</html>