git @ Cat's Eye Technologies The-Dipple / c2c1b62
Not great, but it's a start. catseye 12 years ago
2 changed file(s) with 121 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 <!DOCTYPE html>
1 <head>
2 <meta charset="utf-8">
3 <title>Slide-A-Round</title>
4 <script src="slide-a-round.js"></script>
5 <style>
6 #canvas { border: 1px solid blue; }
7 </style>
8 </head>
9 <body>
10
11 <h1>Silde-A-Round</h1>
12
13 <canvas id="canvas" width="600" height="400" tabindex="0">
14 Your browser doesn't support displaying an HTML5 canvas.
15 </canvas>
16
17 </body>
18 <script type="text/javascript">
19 var canvas = document.getElementById('canvas');
20 canvas.focus();
21 (new SlideARound()).start(canvas);
22 </script>
0 var w = 40;
1 var h = 40;
2
3 Actor = function() {
4 this.init = function(x, y, color) {
5 this.x = x;
6 this.y = y;
7 this.color = color;
8 this.destX = undefined;
9 this.destY = undefined;
10 this.progress = undefined;
11 this.state = 'rest';
12 return this;
13 };
14
15 this.draw = function(ctx) {
16 ctx.beginPath();
17 ctx.fillStyle = this.color;
18 var x = this.x * w + (w / 2);
19 var y = this.y * h + (h / 2);
20 if (this.progress !== undefined) {
21 x += (this.progress / 100) * ((this.destX - this.x) * w);
22 y += (this.progress / 100) * ((this.destY - this.y) * h);
23 }
24 ctx.arc(x, y, w/2, 0, 2 * Math.PI, false);
25 ctx.fill();
26 };
27
28 this.setStateMoving = function(dx, dy) {
29 if (this.state === 'rest') {
30 this.destX = this.x + dx;
31 this.destY = this.y + dy;
32 this.progress = 0;
33 this.state = 'moving';
34 }
35 };
36
37 this.move = function() {
38 if (this.state === 'moving') {
39 this.progress += 10;
40 if (this.progress >= 100) {
41 this.x = this.destX;
42 this.y = this.destY;
43 this.destX = this.destY = this.progress = undefined;
44 this.state = 'rest';
45 }
46 }
47 };
48 };
49
50 SlideARound = function() {
51 var actors;
52 var canvas;
53 var ctx;
54 var intervalId;
55 var counter = 0;
56
57 this.draw = function() {
58 ctx.clearRect(0, 0, canvas.width, canvas.height);
59
60 for (var i = 0; i < actors.length; i++) {
61 actors[i].draw(ctx);
62 actors[i].move();
63 }
64 }
65
66 this.start = function(c) {
67 actors = [];
68 actors.push(new Actor().init(3, 4, "red"));
69 actors.push(new Actor().init(2, 2, "blue"));
70
71 canvas = c;
72 ctx = canvas.getContext('2d');
73
74 canvas.addEventListener('keydown', function(e) {
75 switch (e.keyCode) {
76 case 38: /* Up arrow */
77 actors[0].setStateMoving(0, -1);
78 e.cancelBubble = true;
79 break;
80 case 40: /* Down arrow */
81 actors[0].setStateMoving(0, 1);
82 e.cancelBubble = true;
83 break;
84 case 37: /* Left arrow */
85 actors[0].setStateMoving(-1, 0);
86 e.cancelBubble = true;
87 break;
88 case 39: /* Right arrow */
89 actors[0].setStateMoving(1, 0);
90 e.cancelBubble = true;
91 break;
92 }
93 }, true);
94
95 intervalId = setInterval(this.draw, 25);
96 }
97 }