前端页面index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="global.js"></script>
<script type="text/javascript" src="block.js"></script>
<script type="text/javascript" src="canva.js"></script>
<script type="text/javascript">
window.onload=function (){
initialGloabDom();
startGame();
}
</script>
</head>
<body>
<div style="position: relative;">
<canvas id="layer1" width="1550" height="700" style="border:1px solid #000000;position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="layer2" width="1550" height="700" style="border:1px solid #000000;position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
</body>
</html>
保存全局变量的global.js
g_windowWidth=1550
g_windowHeight=700
function initialGloabDom(){
g_layer1=document.getElementById("layer1");
g_ctxLayer1=g_layer1.getContext('2d');
g_layer2=document.getElementById("layer2");
g_ctxLayer2=g_layer2.getContext('2d');
}
正方形对象 block.js
function Block(x, y, len, color,speed){
this.x = x || 0;
this.y = y || 0;
this.len = len || 10;
this.color = color || 'red';
this.speed = speed ||{
x:1,y:1
}
this.move=function(){
g_ctxLayer1.clearRect(this.x,this.y,this.len,this.len);
g_ctxLayer1.fillStyle = this.color;
this.x += this.speed.x;
this.y += this.speed.y;
g_ctxLayer1.fillRect(this.x,this.y,this.len,this.len);
}
}
Block.startAction = function(block){
setInterval(function(){
block.move();
},100)
}
调用函数canva.js
function startGame(){
let redBlock = new Block(0,0,10,'green',{x:1,y:0});
Block.startAction(redBlock);
}