Canvas (2) 繪製一個棋盤

接下來嘗試繪製一個棋盤,共有 15 個交叉點,14 個間隔,兩邊留白 15px。以橫線的邏輯來解釋,留白 15px,每個間隔 30px,位置從 15px 到 435px。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
window.onload = function() {
var canvas = document.getElementById("canvas");
canvas.width = 1024;
canvas.height = 768;
var cxt = canvas.getContext("2d");
cxt.strokeStyle = "#BFBFBF";

for (var i = 0; i < 15; i++) {
cxt.moveTo(15 + i * 30, 15);
cxt.lineTo(15 + i * 30, 435);
cxt.stroke();
cxt.moveTo(15, 15 + i * 30);
cxt.lineTo(435, 15 + i * 30);
cxt.stroke();
}
};

試試看結果如何

接下來繪製黑白兩色漸層色的棋子,並且讓棋子落在交叉點。其實就是把棋子畫在棋盤交叉點的意思,因此要取用上面的座標。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
oneStep = function(i, j, me) {
//i,j =棋盤上索引, me 黑棋或白棋
cxt.beginPath();
cxt.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * this.Math.PI);
cxt.closePath();
var gradient = cxt.createRadialGradient(
15 + i * 30 + 2,
15 + j * 30 - 2,
13,
15 + i * 30 + 2,
15 + j * 30 - 2,
0
);
if (me) {
gradient.addColorStop(0, "#0a0a0a");
gradient.addColorStop(1, "#636766");
} else {
gradient.addColorStop(0, "#D1D1D1");
gradient.addColorStop(1, "#F9F9F9");
}

cxt.fillStyle = gradient;
cxt.fill();
};

oneStep(0, 0, true);
oneStep(1, 1, false);}

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2020 CYC'S BLOG All Rights Reserved.

UV : | PV :