View difference between Paste ID: Ha6QXSdx and AJvjd9pZ
SHOW: | | - or go back to the newest paste.
1
<!DOCTYPE HTML>
2
3
<html>
4
    <head>
5
        <title>Pastime</title>
6
    </head>
7
    <body>
8-
		<canvas id="canvas" style="border: 1px solid black; position: fixed">This text is displaying if your browser is unable to display HTML5 canvas.</canvas>
8+
		<canvas id="canvas">This text is displaying if your browser is unable to display HTML5 canvas.</canvas>
9
10
		<!-- Adding this for canvas to fill screen -->
11
		<style>
12
			* { margin: 0; padding: 0 }
13
			body, html { height: 100%; overflow: hidden; }
14
			#canvas {
15
				position: absolute;
16
				width: 100%; height: 100%;
17
				border: 1px solid black;
18
			}
19
		</style>
20
    </body>
21
	<script>		
22
		var Box = function(x, y, direction)
23
		{
24
			this.x = x;
25
			this.y = y;
26
			this.direction = direction;
27
		}
28
		
29
		var canvas = document.getElementById("canvas");
30
		var ctx = canvas.getContext("2d");
31
		var snake = [];
32
		var head = new Box(100, 100, -1);
33
		canvas.width = window.innerWidth;
34
		canvas.height = window.innerHeight;
35
		ctx.fillStyle = "red";
36
		
37
		snake.push(head);
38
		//addBox();
39
		//addBox();
40
		//addBox();
41
		
42
		
43
		Box.prototype.draw = function()
44
		{
45
			ctx.fillRect(this.x, this.y, 20, 20);
46
		}
47
		
48
		function drawSnake()
49
		{
50
			//ctx.clearRect(0, 0, canvas.width, canvas.height);
51
			for (var i = 0; i < snake.length; i++)
52
			{
53
				switch (snake[i].direction)
54
				{
55
				case 0:
56
					snake[i].x -= 20;
57
					break;
58
				case 1:
59
					snake[i].y -= 20;
60
					break;
61
				case 2:
62
					snake[i].x += 20;
63
					break;
64
				case 3:
65
					snake[i].y += 20;
66
					break;
67
				}
68
			snake[i].draw();
69
			}
70
		}
71
		
72
		function addBox()
73
		{
74
			var lastBox = snake[snake.length - 1];
75
			var direction = lastBox.direction;
76
			var x, y;
77
			switch (direction)
78
			{
79
			case 0:
80
				x = lastBox.x + 20;
81
				y = lastBox.y;
82
				break;
83
			case 1:
84
				x = lastBox.x;
85
				y = lastBox.y + 20;
86
				break;
87
			case 2:
88
				x = lastBox.x - 20;
89
				y = lastBox.y;
90
				break;
91
			case 3:
92
				x = lastBox.x;
93
				y = lastBox.y - 20;
94
				break;
95
			}
96
			snake.push(new Box(x, y, direction));
97
		}
98
		
99
		document.addEventListener("keydown", function (event)
100
		{
101
			switch (event.keyCode)
102
			{
103
			case 37:
104
				head.direction = 0;
105
				break;
106
			case 38:
107
				head.direction = 1;
108
				break;
109
			case 39:
110
				head.direction = 2;
111
				break;
112
			case 40:
113
				head.direction = 3;
114
				break;
115
			}
116
		}, false);
117
		
118
		function gameLoop()
119
		{
120
			setTimeout("gameLoop()", 100);
121
			drawSnake();
122
		}
123
		
124
		gameLoop();
125
	</script>
126
</html>