HTML5 Canvas Crazy Snake


Open in new window

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
<script src="http://www.html5canvastutorials.com/libraries/kinetic2d-v1.0.0.js">
</script>
<script>
    window.onload = function(){
        var kin = new Kinetic_2d("myCanvas");
        var canvas = kin.getCanvas();
        var context = kin.getContext();
 
        var segments = []; // array of snake body segments
        var angleVariance = 0.2;
        kin.setDrawStage(function(){
 
            var headX, headY;
 
            // get current head position of snake
            if (segments.length > 0) {
                headX = segments[segments.length - 1].x;
                headY = segments[segments.length - 1].y;
                headAngle = segments[segments.length - 1].angle;
            }
            else {
                segments.push({
                    x: canvas.width / 2,
                    y: canvas.height / 2,
                    angle: 0
                });
                headX = canvas.width / 2;
                headY = canvas.height / 2;
                headAngle = 0;
            }
 
            // create new head segment
            var dist = kin.getTimeInterval() / 10;
            var newHeadAngle = headAngle + ((angleVariance / 2) - Math.random() * angleVariance);
 
            var newHeadX = headX + dist * Math.cos(newHeadAngle);
            var newHeadY = headY + dist * Math.sin(newHeadAngle);
 
            // change direction for boundary conditions
            if (newHeadX >= canvas.width || newHeadX <= 0 || newHeadY >= canvas.height || newHeadY <= 0) {
                newHeadAngle += Math.PI / 2;
            }
 
            segments.push({
                x: newHeadX,
                y: newHeadY,
                angle: newHeadAngle
            });
 
            // remove tail segment
            if (segments.length > 75) {
                segments.splice(0, 1);
            }
 
            // draw snake    
            kin.clear();
            context.beginPath();
            context.moveTo(segments[0].x, segments[0].y);
            for (var n = 1; n < segments.length; n++) {
                var segment = segments[n];
                context.lineTo(segment.x, segment.y);
            }
 
            context.lineWidth = 10;
            context.lineCap = "round";
            context.lineJoin = "round";
            context.strokeStyle = "green";
            context.stroke();
 
        });
 
        kin.startAnimation();
    };
</script>