Jordan Baron
Jordan Baron

Reputation: 4200

Canvas not drawing after using

I have a function that, when called, clears the canvas.

function ClearCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}

The problem I'm having is that when I try to draw something onto the canvas again using fillRect() the items I want to draw appear on the bottom of the canvas, only a few of them showing up. The second time I try, nothing shows up.

To see my full code and a test run, go here

var width = 50;
var height = 50;

var interpolate = d3.interpolate('white', 'black');

var elevation = [];
var colormap = [];

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.canvas.width  = window.innerWidth;
ctx.canvas.height = window.innerHeight;

var rectY = 0;

Generate2DArray(elevation, 0, width, height);
Generate2DArray(colormap, 0, width, height);


var gen = new SimplexNoise();

function Generate2DArray(EmptyArray, fill, width, height) {
    for(var i = 0; i < height; i++) {
        EmptyArray.push([]);
        for(var j = 0; j < width; j++) {
            EmptyArray[i][j] = fill;
        }
    }
}

function noise(nx, ny) {
  // Rescale from -1.0:+1.0 to 0.0:1.0
  return gen.noise2D(nx, ny) / 2 + 0.5;
}

function ClearCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}  

function GenTerrain() {


  for(var y = 0; y < height; y++) {
    for(var x = 0; x < width; x++) {      
      var nx = x/width - 0.5, ny = y/height - 0.5;
      elevation[y][x] = noise(nx * 2.57, ny * 2.57);
      colormap[y][x] = interpolate(elevation[y][x]);

      ctx.fillStyle = colormap[y][x];
      ctx.fillRect(x*10, y+rectY, 10, 10);
    }
  rectY += 9
  }
}

Upvotes: 0

Views: 37

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371213

Your rectY is being declared at the top of your code, at the global level:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.canvas.width  = window.innerWidth;
ctx.canvas.height = window.innerHeight;

var rectY = 0;

So, every time GenTerrain runs, it references that variable and adds to it:

rectY += 9

Fix it by encapsulating rectY inside GenTerrain so it starts at 0 each time the function is called.

function GenTerrain() {
  var rectY = 0;
  for(var y = 0; y < height; y++) {
    for(var x = 0; x < width; x++) {      
      var nx = x/width - 0.5, ny = y/height - 0.5;
      elevation[y][x] = noise(nx * 2.57, ny * 2.57);
      colormap[y][x] = interpolate(elevation[y][x]);

      ctx.fillStyle = colormap[y][x];
      ctx.fillRect(x*10, y+rectY, 10, 10);
    }
  rectY += 9
  }
}

Upvotes: 1

Related Questions