JSFiddle - React, Tailwind, and code Playground
HTML
<!-- Here will be Sssssnake -->
<body>
<div class="offset"></div>
<div class="container">
<canvas id="snake" />
</div>
</body>
CSS
* {
box-sizing: border-box;
}
html, body {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
background-color: black;
}
.offset {
height: 10%;
}
.container {
height: 80%;
width: 80%;
margin: 0 auto;
}
canvas {
height: 100%;
width: 100%;
border: 0.5em solid white;
border-radius: 0.5em;
}
JavaScript
function Game(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.ctx.fillStyle = "#ffffff";
this.snake = new Snake(100, 100, 5, 10);
}
Game.prototype.clear = function(){
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
Game.prototype.draw = function(){
this.snake.draw(this.ctx);
};
Game.prototype.frame = function(){
this.clear();
this.snake.step();
this.draw();
};
function Snake(x, y, len, width) {
this.cells = [];
this.direction = 0;
this.speed = 5;
for (var i=0; i<len; i++) {
this.cells.push(new Cell(x, y, width));
}
}
Snake.prototype.step = function(){
this.cells[0].x += Math.cos(this.direction) * this.speed;
this.cells[0].y -= Math.sin(this.direction) * this.speed;
};
Snake.prototype.draw = function(ctx) {
for (var i in this.cells) {
this.cells[i].draw(ctx);
}
};
function Cell(x, y, width) {
this.x = x; this.y = y; this.width = width;
}
Cell.prototype.draw = function(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.width, 0, 2*Math.PI);
ctx.fill();
ctx.closePath();
};
var canvas = document.getElementById("snake");
var game = new Game(canvas);
game.draw();
setInterval(game.frame.bind(game), 1000);