canvas面向對象編程

前端頁面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
//全局Dom對象
/**
 * g_layer1:圖層1
 * g_ctxLayer1:圖層1的畫筆
 * g_layer2:圖層2
 * g_ctxLayer2:圖層2的畫筆
 * @returns
 */
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)
}

//Block.renderMany = function(blocks){
//  let cvs =  document.getElementById("layer1");
//  let ctx = cvs.getContext('2d');
//  setInterval(function(){
//    ctx.clearRect(0,0,400,400);
//    for(let block of blocks){
//        ctx.fillStyle = block.color;
//        ctx.fillRect(block.x,block.y,block.len,block.len);
//        block.move();
//    }
//  },100)
//}

調用函數canva.js

function startGame(){
    let redBlock = new Block(0,0,10,'green',{x:1,y:0});
    Block.startAction(redBlock);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章