JSFiddle - React, Tailwind, and code Playground
by Thornton_Fernbacher
HTML
<div><canvas id="canvas"></canvas></div>
CSS
div{
width:400px;
height:400px;
}
JavaScript
var snake = [{x: 70,y: 0}, {x: 60,y: 0}, {x: 50,y: 0}, {x: 40,y: 0}, {x: 30,y: 0}, {x: 20,y: 0}, {x: 10,y: 0}, {x: 0,y: 0}];
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var direction = 1;
var alive = true;
var timer = 0;
var speed = 6;
var color = "rgb(116, 244, 66)";
var pickup = {
x: 40,
y: 60,
lifetime: 0,
spawn:function() {
this.lifetime = 0;
fadeOutColor(66, 244, 80);
this.x = Math.floor(Math.random() * (canvas.width /scale / 10)) * 10;
this.y = Math.floor(Math.random() * (canvas.height /scale / 10)) * 10;
console.log(this.x,this.y);
},draw:function() {
console.log(color);
ctx.fillStyle = color;
ctx.fillRect(this.x + 1.5, this.y + 1.5, 7, 7);
}};
var particle = {
}
var scale = 1;
pickup.spawn();
if(window.innerHeight < window.innerWidth) {
var size = window.innerHeight;
scale = size/200;
ctx.canvas.height = size;
ctx.canvas.width = size;
ctx.scale(scale,scale);
} else {
var size = window.innerWidth;
scale = window.innerWidth/200;
ctx.canvas.height = size;
ctx.canvas.width = size;
ctx.scale(scale,scale);
}
draw();
function draw() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width/scale, canvas.height/scale);
pickup.draw();
ctx.fillStyle = "#FF0000";
for (c in snake) {
ctx.fillRect(snake[c].x, snake[c].y, 10, 10);
}
if (timer == speed && alive) {
Move();
timer = 0;
}
timer++;
requestAnimationFrame(draw);
}
document.onkeydown = function(e) {
if (e.keyCode == 37) {
direction = direction == 1 ? 1 : 3;
}
if (e.keyCode == 38) {
direction = direction == 2 ? 2 : 0;
}
if (e.keyCode == 39) {
direction = direction == 3 ? 3 : 1;
}
if (e.keyCode == 40) {
direction = direction == 0 ? 0 : 2;
}
if (e.keyCode == 65) {
AddLength(2);
}
};
function Move() {
var newX = snake[0].x;
var newY = snake[0].y;
var oldX;
var oldY;
if (direction == 0) {
newY = snake[0].y - 10;
}
if (direction == 1) {
newX =...