Barrie Reader
Barrie Reader

Reputation: 10713

Redrawing a section of canvas (based upon a grid)

I have some perlin noise generating a "map": http://jsfiddle.net/rossc1/RKCdZ/ (updated to work on JSFiddle - Thanks @Ross)

What I really want is to only redraw the section around the "reddot" (use WASD to move).

It does, technically, work but the offset it wrong and it redraws the map wrong :( I've been battling with this for a little while. Cheers for your help!

p.s. Ignore the fact that there is no error checking :)

p.p.s This is the section that is causing me hassle:

function updateMap() {
    //update display functions here

    for (x = yX-8; x <= yX+8; x++) {
        for (y = yY-8; y <= yY+8; y++) {

            if (x >= 0 && y >= 0 && x < mapSize && y < mapSize) {

                if (perlin[x][y] === 0) {
                    rect(7*(x),7*(y), 7, 7, '#6fb4db'); //water
                } else {
                    rect(7*(x),7*(y), 7, 7, 'rgb('+perlin[x][y]+','+ (perlin[x][y] + 50) +','+perlin[x][y]+')'); //land
                }

                if (x === yX && y === yY) {
                    rect(7*(x),7*(y), 7, 7, 'rgb(225,0,0)'); //you
                }

            }

        }
    }   
}

Upvotes: 2

Views: 138

Answers (1)

Simon Sarris
Simon Sarris

Reputation: 63812

Oh dear! I know why. You're gonna hate this one.

ctx.rect and ctx.fillRect are NOT the same thing! rect is for paths only and fillRect does not use paths. You are making a path, using fillRect with the previous color, and then closing your completely empty path! So make one of two changes:

    function rect(x,y,w,h,col) {
        ctx.beginPath();
        // rect and not fillRect!
        ctx.rect(x,y,w,h);
        if (col) {
            ctx.fillStyle = col;
        }
        //ctx.stroke();
        ctx.closePath();
        ctx.fill();
    }

Or:

    function rect(x,y,w,h,col) {
        // set fillStyle BEFORE calling fillRect!
        if (col) {
            ctx.fillStyle = col;
        }
        ctx.fillRect(x,y,w,h);
    }

Example: http://jsfiddle.net/RKCdZ/6/

In other words your math was right all along! You were just filling each square with the previous color.

Upvotes: 2

Related Questions