SOURCE

console 命令行工具 X clear

                    
>
console
let huabu = document.getElementById("hua");

var mkais = document.getElementById("kais");

let youxi = huabu.getContext("2d")

var shiwux = 10 * 30, shiwuy = 10 * 30, ischi = false, jieshu = false;

var mdata = [{ x: 3, y: 0 }, { x: 2, y: 0 }, { x: 1, y: 0 }];
var mmdata = mdata;
//移动方向
var yidx = 1, yidy = 0;

var kais = false;

document.addEventListener("keydown", function (e) {
    if (e.keyCode === 37) {
        yidx = -1;
        yidy = 0;
    } else if (e.keyCode === 38) {
        yidx = 0;
        yidy = -1;
    } else if (e.keyCode === 39) {
        yidx = 1;
        yidy = 0;
    } else if (e.keyCode === 40) {
        yidx = 0;
        yidy = 1;
    }
}, false);

initdata();

function initdata() {

    setInterval(function () {
        if (jieshu) {
            return;
        }
        youxi.clearRect(0, 0, 600, 600);

        if (ischi) {
            shiwux = Math.floor(Math.random() * 20) * 30;
            shiwuy = Math.floor(Math.random() * 20) * 30;
        }

        youxi.fillStyle = "#cccc00";
        youxi.beginPath();//开始绘制
        youxi.arc(shiwux + 15, shiwuy + 15, 15, 0, 2 * Math.PI);//arc 的意思是“弧”
        youxi.fill();//开始填充
        youxi.strokeStyle = "#934342";//将线条颜色设置为蓝色
        youxi.stroke();//stroke() 方法默认颜色是黑色(如果没有上面一行,则会是黑色)
        for (let i = 0; i < mdata.length; i++) {
            if (i == 0) {
                youxi.fillStyle = "#232345";
            } else {
                youxi.fillStyle = "#cccc00";
            }
            youxi.beginPath();//开始绘制
            youxi.arc(mdata[i].x * 30 + 15, mdata[i].y * 30 + 15, 15, 0, 2 * Math.PI);//arc 的意思是“弧”
            youxi.fill();//开始填充
            youxi.strokeStyle = "blue";//将线条颜色设置为蓝色
            youxi.stroke();//stroke 

        }
        mkais.onclick = function () {
            if (kais == true) {

            }
            kais = true;
        }

        if (kais == false) {
            return;
        }
        if (mdata[0].x * 30 === shiwux && mdata[0].y * 30 === shiwuy) {
            ischi = true;
        } else {
            ischi = false;
            mdata.pop();
        }

        var addzhuju = mdata[0];
        var adds = {
            x: addzhuju.x + yidx,
            y: addzhuju.y + yidy,
        };


        if (addzhuju.x < 0 || addzhuju.x > 19 || addzhuju.y < 0 || addzhuju.y > 19) {
            jieshu = true;
            alert("你以死亡");

        } else {
            mdata.unshift(adds);
            //绘制蛇
        }
        youxi.fill();

    }, 1000 / 3);
}
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>贪吃蛇画布</title>
	<style>
		canvas {
			display: block;
			margin: 0 auto;
			background: #B0C4DE;
		}
	</style>

</head>

<body>
	<button id="kais">开始游戏</button>
	<canvas width="600" height="600" id="hua"></canvas>
	<script src="main.js">

	</script>
</body>

</html>