Javascript drawing pane with columns of alternating colors using ctx
I would like to write some javascript code to make the boards appear like in this image:
1
This is my code:
function draw() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x, y;
for (y=0; y<100; y+=10) {
for (x=0; x<100; x+=5) {
if ((x+y)%10 == 0) {
ctx.fillStyle = "black";
}
else {
ctx.fillStyle = "white";
}
ctx.fillRect(x, y, 10, 10);
}
}
}
It currently only displays vertical lines. What changes do I need to make to make it look like an image?
+3
source to share
2 answers
You have to divide your x value by the increment (10) and check it modulo 2:
function draw() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
for (var y = 0; y < 100; y += 10) {
for (var x = 0; x < 100; x += 10) {
if ((x/10) % 2 == 0) {
ctx.fillStyle = "black";
} else {
ctx.fillStyle = "red";
}
ctx.fillRect(x, y, 7, 7);
}
}
}
draw()
<canvas id="canvas" height="100" width="100"></canvas>
0
source to share
I prefer that my loops are always incremented by 1 and multiplied by the size I want. It helps you to better deal with difficult tasks. Then I just mod by 2 because it's easier to read than division by increment. It also allows you to customize your grid more clearly.
function draw() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x, y;
var xWidth = 10;
var yWidth = 10;
for (x=0; x<10; x++) {
if( x % 2 === 0)
{
ctx.fillStyle = "white";
} else {
ctx.fillStyle = "black";
}
for( y = 0; y < 10 ; y++)
{
ctx.fillRect(x * xWidth, y * yWidth, 10, 10);
}
}
}
0
source to share