Reputation: 10713
Hey I have the following functions:
function rect(x,y,w,h,col) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.lineWidth = '1px';
ctx.fillStyle = col;
ctx.stroke();
ctx.closePath();
ctx.fill();
}
function showMap() {
canvas = document.getElementById('map_console');
ctx = canvas.getContext('2d');
for (var y = 0; y < world.length; y++) {
for (var x = 0; x < world[y].length; x++) {
rect(6*(y+6),6*(x+6),6,6,world[posY][posX].bgCol);
}
}
However, when I run this - all the rectangles on the canvas are the same colour... I'm obviously not iterating through the loop properly :(
Any ideas?
Note:
world[posY][posX].bgCol
is a random hex colour...
Upvotes: 1
Views: 53
Reputation: 8230
I made some adjustments and additions to your code and all works in my tests in FF, Chrome, Opera: HTML:
<canvas id="map_console" width="300px" height="500px"></canvas>
SCRIPT:
function randColor() {
var str=Math.round(16777215*Math.random()).toString(16);
return "#000000".substr(0,7-str.length)+str;
}
var xSize=6,ySize=8;
var world=[];
for(var x=0;x<xSize;x++) {
world[x]=[];
for(var y=0;y<ySize;y++)
world[x][y]={bgCol:randColor()};
}
function rect(x,y,w,h,col) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.lineWidth = '1px';
ctx.fillStyle = col;
ctx.stroke();
ctx.closePath();
ctx.fill();
}
function showMap() {
canvas = document.getElementById('map_console');
ctx = canvas.getContext('2d');
for (var x = 0; x < world.length; x++) {
for (var y = 0; y < world[x].length; y++) {
rect(40*x,40*y,40,40,world[x][y].bgCol);
}
}
}
showMap();
this sample in jsfiddle.net: http://jsfiddle.net/dMSE5/
Upvotes: 1