好的,所以我正在尝试在Javascript / Canvas中创建一个国际象棋游戏。我仍然是JS的新手,所以请原谅我缺乏理解。
我目前有以下代码来生成网格,但是,它只创建一行方块而不填充整个画布区域。
var SQUARE_SIZE;
const NUMBER_OF_ROWS = 5;
const NUMBER_OF_COLS = 5;
var NUMBER_OF_SQUARES;
var xValue = 0;
var yValue = 0;
var canvas, ctx
window.onload = function()
{
canvas = document.getElementById("chessBoard");
ctx = canvas.getContext("2d");
SQUARE_SIZE = canvas.height / NUMBER_OF_ROWS;
NUMBER_OF_SQUARES = NUMBER_OF_ROWS * NUMBER_OF_COLS;
console.log("Size of each square = " + SQUARE_SIZE +"px");
drawBoard();
}
function drawBoard()
{
for (var blockTotal = 0; blockTotal < NUMBER_OF_SQUARES; blockTotal++)
{
if (blockTotal % 2)
{
xValue += SQUARE_SIZE;
ctx.fillStyle = '#663300';
ctx.fillRect(xValue, yValue, SQUARE_SIZE, SQUARE_SIZE);
}
else
{
xValue += SQUARE_SIZE
ctx.fillStyle = '#eeeed2';
ctx.fillRect(xValue, yValue, SQUARE_SIZE, SQUARE_SIZE);
}
xValue = 0;
yValue += SQUARE_SIZE;
}
// Outline of board
ctx.lineWidth = 5;
ctx.strokeRect(0, 0, NUMBER_OF_ROWS * SQUARE_SIZE, NUMBER_OF_COLS * SQUARE_SIZE);
}
我做错了什么?
答案 0 :(得分:1)
您应该使用window.addEventListener(&#39; load&#39;,function(){...})而不是window.onload = function(){...}。你也应该使用嵌套循环,它们在大多数情况下更简单。
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 8; j++) {
ctx.beginPath();
ctx.fillStyle = ["#eeeed2", "#630"][(i + j) % 2];
ctx.fillRect(j * 20, i * 20, 20, 20);
ctx.closePath();
}
}
答案 1 :(得分:0)
检查出来:
var SQUARE_SIZE;
const NUMBER_OF_ROWS = 5;
const NUMBER_OF_COLS = 5;
var NUMBER_OF_SQUARES;
var xValue = 0;
var yValue = 0;
var canvas, ctx
window.onload
canvas = document.getElementById("chessBoard");
ctx = canvas.getContext("2d");
SQUARE_SIZE = canvas.height / NUMBER_OF_ROWS;
NUMBER_OF_SQUARES = NUMBER_OF_ROWS * NUMBER_OF_COLS;
console.log("Size of each square = " + SQUARE_SIZE +"px");
drawBoard(canvas, NUMBER_OF_ROWS, NUMBER_OF_COLS);
function drawBoard(can, nRow, nCol) {
var ctx = can.getContext("2d");
var w = can.width;
var h = can.height;
nRow = nRow || 8; // default number of rows
nCol = nCol || 8; // default number of columns
w /= nCol; // width of a block
h /= nRow; // height of a block
for (var i = 0; i < nRow; ++i) {
for (var j = 0, col = nCol / 2; j < col; ++j) {
ctx.rect(2 * j * w + (i % 2 ? 0 : w), i * h, w, h);
}
}
ctx.fill();
}
&#13;
<canvas id="chessBoard" width="400" height="400"/>
&#13;