var chessBoard=[];
for(var i=0;i<16;i++){
chessBoard[i]=[];
for(var j=0;j<16;j++){
chessBoard[i][j]=0;
}
}
var chess = document.getElementById('canvas1');
var context = chess.getContext('2d');
context.strokeStyle = '#eee';
var logo = new Image();
logo.src = './image/beijing.png';
logo.onload = function() {
context.drawImage(logo, 0, 0, 405, 405);
drawLine();
oneStep(2, 2, true);
oneStep(3, 3, false);
}
function oneStep(i, j, me) {
context.beginPath();
context.arc(15 + i * 25, 15 + j * 25, 10, 0, 2 * Math.PI);
var gradient = context.createRadialGradient(15 + i * 25 + 2, 15 + j * 25 - 2, 6, 15 + i * 25 + 2, 15 + j * 25 - 2, 3);
if (me) {
gradient.addColorStop(0, '#0a0a0a');
gradient.addColorStop(1, '#ccc');
} else {
gradient.addColorStop(0, '#ddd');
gradient.addColorStop(1, '#fff');
}
context.fillStyle = gradient;
context.closePath();
context.fill();
}
/*这个函数用来画棋盘*/
function drawLine() {
for (var i = 0; i < 16; i++) {
context.moveTo(15 + 25 * i, 15);
context.lineTo(15 + 25 * i, 390);
context.moveTo(15, 15 + 25 * i);
context.lineTo(390, 15 + 25 * i);
context.stroke();
}
}
chess.onclick=function(){
console.log(chessBoard[i][j]);
}
二维数组打印的时候就会提示qizi.js:50 Uncaught TypeError: Cannot read property '16' of undefined不管这个数字设置多大都会出错,有遇到过同样问题的吗?顺便求解答
chess.onclick=function(){
console.log(chessBoard[i][j]);
}
这个代码有问题,点击的时候都没有去获取鼠标点击的坐标值offsetX和offsetY。。
for循环中i,j《15,因为i,j是从0开始循环的,0~14正好十五条线
chess.onclick=function(){
console.log(chessBoard[i][j]);
}
里面的‘i’跟‘j’经过for循环后已经变成16了。而chessBoard最大是chessBoard[15][15];数组越界了