Macro Da

每天学一点,成长多一点!

练习:用canvas画“井字游戏”

初学canvas,做个练习。代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>井字游戏</title>
</head>
<body>
<canvas id="well" width="500" height="500" style="display: block; margin: 0 auto;"></canvas>
<script>
	var well = document.getElementById("well");
	var w = well.width;    //获取宽度
	var h = w;             //获取高度,与宽度保持一致
	var p = w * 0.07;      //网格的内距
	var r = w / 3 / 2 - p; //圆棋子的半径
	
	function chessboard(wlc){
		//画外部线框
		wlc.strokeRect(0, 0, w, h);

		//开始画网格
		wlc.beginPath();
		//画第一列线
		wlc.moveTo(w * 1 / 3, 0);
		wlc.lineTo(w * 1 / 3, h);
		//画第二列线
		wlc.moveTo(w * 2 / 3, 0);
		wlc.lineTo(w * 2 / 3, h);
		//画第一行线
		wlc.moveTo(0, h * 1 / 3);
		wlc.lineTo(w, h * 1 / 3);
		//画第二行线
		wlc.moveTo(0, h * 2 / 3);
		wlc.lineTo(w, h * 2 / 3);

		wlc.stroke();
	}
	
	
	function xPiece(wlc, path){
		wlc.beginPath();
		var shang = parseInt(path / 3);  //判断Y轴位置   1
		var yu = path % 3;               //判断X轴位置   0
		
		var m1xS = w / 3 * yu + p;              //第一条斜线的开始点X轴
		var m1yS = h / 3 * shang + p;           //第一条斜线的开始点Y轴
		var m1xE = w / 3 * yu + p + r * 2;      //第一条斜线的结束点X轴
		var m1yE = h / 3 * shang + p + r * 2;   //第一条斜线的结束点Y轴
		
		var m2xS = w / 3 * yu + p + r * 2;      //第二条斜线的开始点X轴
		var m2yS = h / 3 * shang + p;           //第二条斜线的开始点Y轴
		var m2xE = w / 3 * yu + p;              //第二条斜线的结束点X轴
		var m2yE = h / 3 * shang + p + r * 2;   //第二条斜线的结束点Y轴
		
		
		//画一个叉棋子,位于中间
		wlc.moveTo(m1xS, m1yS);
		wlc.lineTo(m1xE, m1yE);
		wlc.moveTo(m2xS, m2yS);
		wlc.lineTo(m2xE, m2yE);

		wlc.stroke();
	}
	
	function roundPiece(wlc, path){
		wlc.beginPath();
		var shang = parseInt(path / 3);  //判断Y轴位置   1
		var yu = path % 3;               //判断X轴位置   0
		var x = w / 3 * yu + w / 6;      //计算X轴
		var y = h / 3 * shang + h / 6;   //计算Y轴
		wlc.arc(x, y, r, 0, 2 * Math.PI);
		wlc.stroke();
	}
	
	
	
	function drawWell(){
		var wlc = well.getContext("2d");
		chessboard(wlc);   //画棋盘
		
		xPiece(wlc,1);        //画叉棋子
		xPiece(wlc,6);        //画叉棋子
		xPiece(wlc,4);        //画叉棋子
		xPiece(wlc,8);        //画叉棋子
		
		roundPiece(wlc, 0);   //画圆棋子
		roundPiece(wlc, 2);   //画圆棋子
		roundPiece(wlc, 3);   //画圆棋子
		roundPiece(wlc, 5);   //画圆棋子
		roundPiece(wlc, 7);   //画圆棋子
		
	}
	drawWell();
</script>
</body>
</html>

 

点赞

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注