重新绘制相同的画布线不正确

时间:2018-09-19 09:08:11

标签: javascript html html5-canvas

我有一个简单的canvas元素:

<canvas id="floor" style="background-color:#f7f7f7;border:1px #000 solid;"    >
</canvas>

我还有一个draw函数,它创建垂直/水平线:

function draw(){

  ctx.translate(0.25, 0.25);
  for (var x = size; x < canvas.width; x += size)  { //vertical
      ctx.moveTo(x, 0);
      ctx.lineTo(x, canvas.height);
  }

  for (var y = size; y < canvas.height; y += size) { //horizontal
     ctx.moveTo(0, y);
     ctx.lineTo(canvas.width, y);
  }

  ctx.strokeStyle = "#C1C1C1";
  ctx.stroke();
}

结果:

enter image description here

按钮再次调用此draw函数:

$(".b").on('click',function (){
  draw();
})

但是,如果我多次单击此按钮,则似乎添加了更多行,使其看起来更粗:

enter image description here

问题

如果我画完全相同的线,为什么画布看起来不一样?

我该如何修复我的代码以使其看起来相同?

JSBIN

2 个答案:

答案 0 :(得分:2)

每次致电draw时,您需要使用以下方法开始新的路径: ctx.beginPath();

答案 1 :(得分:1)

您需要在重新绘制线条之前清除画布并使用上下文开始路径方法:

ctx.clearRect(0, 0, canvas.width, canvas.height);

var canvas = document.getElementById('floor');
var ctx = canvas.getContext("2d");

var size = 20

function draw(){
	ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  //ctx.translate(0.25, 0.25);
  
  //this is important!
  ctx.beginPath();
  
  for (var x = size; x < canvas.width; x += size)  { //vertical
      ctx.moveTo(x, 0);
      ctx.lineTo(x, canvas.height);
  }

  for (var y = size; y < canvas.height; y += size) { //horizontal
     ctx.moveTo(0, y);
     ctx.lineTo(canvas.width, y);
  }

  ctx.strokeStyle = "#C1C1C1";
  ctx.stroke();
   
}

document.getElementById('button').addEventListener('click', draw);
<canvas id="floor" style="background-color:#f7f7f7;border:1px #000 solid;"    >
</canvas>

<button id="button">
redraw
</button>