-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathship_code_canvas.html
More file actions
98 lines (72 loc) · 1.98 KB
/
Copy pathship_code_canvas.html
File metadata and controls
98 lines (72 loc) · 1.98 KB
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
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<style>
#canvas {
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas= document.getElementById("canvas");
canvas.width = "1000";
canvas.height = "800";
var ctx = canvas.getContext("2d");
// var ship = {
// x: 100,
// y: 100,
// vx: 2,
// vy: 2
// };
function Ship (x, y) { // this is a constructor function for many ships!
this.x = x;
this.y = y;
this.vx = 5;
this.vy = 5;
}
var ships= [];
var mouseCoords = {x : 0, y : 0};
function update() {
ships.push(new Ship(mouseCoords.x, mouseCoords.y));
for (var i = 0; i < ships.length; i++ ){
var ship = ships[i];
var angle = Math.atan2(mouseCoords.y - ship.y, mouseCoords.x - ship.x);
var x_part = Math.cos(angle);
var y_part = Math.sin(angle);
ship.vx += x_part * 0.2;
ship.vy += y_part * 0.2;
ship.x += ship.vx;
ship.y += ship.vy;
}
}
function draw() {
ctx.fillStyle="#255";
ctx.fillRect(0, 0, 1000, 800);
for (var i = 0; i < ships.length; i++) {
ctx.beginPath();
ctx.arc(ships[i].x, ships[i].y, 10, 0, Math.PI * 2);
ctx.fillStyle = "#ffff00";
ctx.fill();
}
}
function loop () {
update();
draw();
window.requestAnimationFrame(loop);
}
loop();
canvas.addEventListener("click", function(evt) {
var rect = canvas.getBoundingClientRect();
ships.push(new Ship(evt.clientX - rect.left, evt.clientY - rect.top));
});
canvas.addEventListener("mousemove", function(evt) {
var rect = canvas.getBoundingClientRect(); // x & y of the canvas
mouseCoords.x = evt.clientX - rect.left;
mouseCoords.y = evt.clientY - rect.top;
});
</script>
</body>
</html>