我做了个可以用户设置五子棋棋盘大小的demo,但是只有15*15才是正常的。怎么回事?
/**
* Created by Administrator on 2017/3/11 0011.
*/
window.onload = function () {
var button = document.getElementById("button");
var buttonClickNum = 0;
button.addEventListener('click', function () {
var cols = document.getElementsByTagName('input')[0].value;
if (cols != 0 && buttonClickNum == 0) {
chess(cols);
buttonClickNum++;
} else if (buttonClickNum != 0) {
alert('请刷新再输入~')
} else {
alert("请输入棋盘大小!");
}
})
};
var chess = function (cols) {
var chess = document.getElementById("chess");
chess.style.width = cols * 30 + 'px';
chess.style.height = cols * 30 + 'px';
var context = chess.getContext('2d');
var me = true;
var chessBoard = [];
for (var z = 0; z < cols; z++) {
chessBoard[z] = [];
for (var x = 0; x < cols; x++) {
chessBoard[z][x] = 0;
}
}
// drawChessBoard();
//画棋盘线
context.strokeStyle = '#bfbfbf';
for (var i = 0; i < cols; i++) {
context.moveTo(15 + i * 30, 15);
context.lineTo(15 + i * 30, cols * 30 - 15);
context.stroke();
context.moveTo(15, 15 + i * 30);
context.lineTo(cols * 30 - 15, 15 + i * 30);
context.stroke();
}
;
//创建黑白棋子调用函数
var oneStep = function (i, j, me) {
//beginPath,closePath,arc 调用方法绘制圆
context.beginPath();
context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
context.closePath();
//调用圆心渐变的函数,通过addColorStop绘制起始和终止的渐变色
var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 + 2, 10, 15 + i * 30 + 2, 15 + j * 30 + 2, 3);
if (me) {
gradient.addColorStop(0, '#0a0a0a');
gradient.addColorStop(1, "#636766");
} else {
gradient.addColorStop(0, '#D0D0D0');
gradient.addColorStop(1, "#F9F9F9");
}
//fillstyle,填充颜色,fill填充
context.fillStyle = gradient;
context.fill();
};
chess.onclick = function (e) {
var x = e.offsetX;
var y = e.offsetY;
console.log(x+"\t"+y);
var i = Math.floor(x / 30);
var j = Math.floor(y / 30);
if (chessBoard[i][j] == 0) {
oneStep(i, j, me);
if (me) {
chessBoard[i][j] = 1;
} else {
chessBoard[i][j] = 2;
}
me = !me;
}
}
};