Barrie Reader
Barrie Reader

Reputation: 10713

individual fills for individual rectangles

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

Answers (2)

Andrew D.
Andrew D.

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

Py.
Py.

Reputation: 3599

There must be something wrong outside of this code.

A quick test here is working perfectly.

This only differ from your code in the place the call to the world variable are done.

And the fact that ctx is a global variable (which is probably your case as well).

Upvotes: 0

Related Questions