Reputation:
I am having trouble making a checkered canvas background. The screen presently displays a solid color filling the whole screen. This color is the fillStyle in the else
statement under the two for
loops. Am I using the modulus operator wrong? or is it something else?
function createBackground(){
if(!Modernizr.canvas) return;
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
background = $('#game .background')[0],
rect = background.getBoundingClientRect(), //returns the dimension of background
gradient,
monsterSize = monstr.settings.monsterSize;
canvas.width = rect.width;
canvas.height = rect.height;
context.scale(rect.width, rect.height);
/* create checker */
cols = canvas.width / monsterSize;
rows = canvas.height / monsterSize;
console.log(cols); //8
console.log(rows); //12
console.log(monsterSize); //40
for (var i=0; i<cols; i++){
for (var j=0; j<rows; j++){
if((i+j)% 2){ /* for every other block */
context.fillStyle = '#262626';
context.fillRect(i*monsterSize, j*monsterSize, monsterSize, monsterSize);
} else {
context.fillStyle = '#E8E8E8';
context.fillRect(i*monsterSize, j*monsterSize, monsterSize, monsterSize);
}
};
};
/* add canvas to html element */
background.appendChild(canvas);
}**
Upvotes: 1
Views: 1662
Reputation: 71918
You are scaling the canvas wrong, making every tile on the checkerboard so big, that you can only see a single tile on the screen.
Comment this line out:
context.scale(rect.width, rect.height);
Or try replacing the values you pass with smaller numbers like 1
, 2
, etc, depending on the the amount of scaling you want - if you even need scaling.
See demo.
Upvotes: 3