使用后画布不画画

时间:2018-04-27 00:30:18

标签: javascript html5 html5-canvas

我有一个函数,在调用时,清除画布。

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

我遇到的问题是,当我尝试使用fillRect()再次在画布上绘制某些内容时,我想要绘制的项目显示在画布的底部,只显示其中一些。我第二次尝试,没有任何东西出现。

要查看我的完整代码和测试运行,请转到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
  }
}

1 个答案:

答案 0 :(得分:1)

您的rectY被声明在代码的顶部,在全球范围内:

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

var rectY = 0;

因此,每次GenTerrain运行时,它都会引用该变量并添加到其中:

rectY += 9

通过将rectY封装在GenTerrain内来修复它,以便每次调用该函数时都从0开始。

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
  }
}