js canvas实现俄罗斯方块实现俄罗斯方块
本文实例为大家分享了canvas实现俄罗斯方块的具体代码,供大家参考,具体内容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="margin: 0;">
<canvas id="tetris" style="border: 1px solid #000;"></canvas>
<div id="text" style='color: red;font-size: 30px;'>当前分数:0</div>
</body>
<script>
let cav = document.getElementById('tetris')
let text = document.getElementById('text')
let ctx = cav.getContext('2d')
let k = 40 //倍数
let speed = 1000
let grade = 0
let restartFlag = false
let timer = null
let curGraphPositionList = [] let curtype = undefined
let transformNum = 0
let blockGraph = Array(10)
let beforeUpdateGraph = [] for(let i = 0;i<blockGraph.length;i++){
blockGraph[i] = Array(20)
}
cav.width = 10*k
cav.height = 20*k
ctx.fillStyle="yellow"
ctx.strokeStyle="black"
function ramdomRectType(){
return Math.floor((Math.random()*7)+1)
}
function randomXposition(){
return Math.floor(Math.random()*10)
}
function drawRect(position,width){
ctx.beginPath()
ctx.rect(position[0],position[1],width,width)
ctx.fill();
ctx.stroke()
}
function drawGraph(positionList){
if(positionList.length===0){
return
}
for(let item of positionList){
let x= item[0]*k
let y= item[1]*k
let position = [x,y] drawRect(position,k)
}
}
function isOut(position,xOry){//x:0,y:1
if(xOry===0){
if(position<0||position>9){
return true
}else{
return false
}
}else{
if(position<0||position>19){
return true
}else{
return false
}
}
}
function randomRectShape(){
let rposition = randomXposition()
let type = ramdomRectType()
curtype = type
transformNum = 0
let positionList = [] let one = [] let two = [] let three = [] let four = [] switch(type){
case 1: