學(xué)習(xí)Canvas可以通過一些例子來增加成就感
一下是一個輸出一個象棋棋盤的例子
<html>
<body>
<canvas id="canvas1" width="560" height="620"></canvas>
<script type="text/javascript">
//以要畫的點為原點定義四個象限
var pointDefine=[[-1,-1],[1,-1],[-1,1],[1,1]];
//要繪制標(biāo)記方位 全部
var allP =[0,1,2,3];
//要繪制標(biāo)記方位 左側(cè)
var leftP =[1,3];
//要繪制標(biāo)記方位 右側(cè)
var rightP =[0,2];
var cl = 70;
/**
* 炮和兵位置信息
* 每一組位置信息為撮抓,橫向位置磷醋,縱向位置忿檩,縱向位置上與之相對應(yīng)的點的距離嗅辣,要繪制標(biāo)記方位(左側(cè)還是右側(cè)還是全部)
*/
var points=[
[0,3,3,leftP],
[8,3,3,rightP],
[2,3,3,allP],
[4,3,3,allP],
[6,3,3,allP],
[1,2,5,allP],
[7,2,5,allP]
];
var pointPlace = function (ctx,x,y,pointInfo){
var l = 10;
var space = 3;
for ( var i = 0; i <pointInfo.length; i++){
var xinfo = pointDefine[pointInfo[i]][0];
var yinfo = pointDefine[pointInfo[i]][1];
ctx.moveTo(x+xinfo*space,y+yinfo*l);
ctx.lineTo(x+xinfo*space,y+yinfo*space);
ctx.lineTo(x+xinfo*l,y+yinfo*space);
}
}
var drawX = function (ctx,x,y){
ctx.moveTo((x-1)*cl,(y-1)*cl);
ctx.lineTo((x+1)*cl,(y+1)*cl);
ctx.moveTo((x+1)*cl,(y-1)*cl);
ctx.lineTo((x-1)*cl,(y+1)*cl);
}
var drawProitPare = function (ctx,x,y,cl){
pointPlace(ctx,x,y,allP);
pointPlace(ctx,x,y +cl*5,allP);
}
var drawProitPare = function (ctx,x,y,yplus,cl,pointP){
pointPlace(ctx,cl*x,cl*y,pointP);
pointPlace(ctx,cl*x,cl*y +cl*yplus,pointP);
}
/**
* 畫象棋棋盤
*/
var drawTable = function(ctx){
for(var clo = 0;clo<8 ;clo++){
for(var ln = 0;ln<9 ;ln++){
if(ln!=4){
ctx.strokeRect(clo*cl,ln*cl,cl,cl);
}else{
ctx.strokeRect(0,ln*cl,cl*8,cl);
}
}
ctx.strokeRect(0,0,560,620);
}
}
var canvas1 = document.getElementById("canvas1");
var ctx = canvas1.getContext("2d");
//設(shè)置線寬 線的顏色
ctx.lineWidth = 1;
ctx.strokeStyle = "dodgerblue";
drawTable(ctx);
var ctx2 = canvas1.getContext("2d");
drawX(ctx2,4,1);
drawX(ctx2,4,8);
for(var i = 0; i <points.length; i++){
drawProitPare(ctx2,points[i][0],points[i][1],points[i][2],cl,points[i][3]);
}
ctx2.strokeStyle = "dodgerblue";
ctx2.font='bolder 48px 隸書';
ctx2.rotate(90 * Math.PI/180)
ctx2.strokeText("漢",cl*4+10,-485);
ctx2.strokeText("界",cl*4+10,-435);
ctx2.rotate(-180 * Math.PI/180)
ctx2.strokeText("楚",-(cl*5-10),70);
ctx2.strokeText("河",-(cl*5-10),120);
ctx2.stroke();
</script>
</body>
</html>