Search code examples
htmlrecursionhtml5-canvasrectangles

Translate a rectangle in canvas


I am unable to clear a rectangle completely using clearRect method which is being translated on canvas across X direction. The problem can be seen live at JS Bin - Link to demo

JS code

(function() {  

  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');

  context.fillStyle = '#ccc';
  context.fillRect(0, 0, 100, 50); //x,y,w,h

  translate(canvas, context, 0, 0, 100, 50, 'x', 5);

  function translate(canvas, context, x, y, w, h, direction, interval) {
    context.fillRect(x, y, w, h);

    if (direction == 'x') {
      if ((x + interval + w >= canvas.width) || (x + interval < 0)) interval = -1 * interval;

      setTimeout(function() {
        context.clearRect(x, y, w, h);
        translate(canvas, context, x + interval, y, w, h, direction, interval);
      }, 1000);
    }
  }

}());

It is leaving traces before moving forward/backward. And I have used the same dimensions to clear the rectangle which were used to draw it.

Please observe the complete path for observing the problem.


Solution

  • IE10 and FF21 work fine, Chrome gives the "remnants".

    Even then, I can't consistently reproduce the misbehaving effect.

    Also notice that when you scroll your jsbin results panel the remnants go away. So Chrome becomes aware that these remnant pixels shouldn't be there.

    Looks like yet another canvas bug in Chrome (possibly, but not necessarily, related to anti-aliasing).

    You could hack at it by extending your clear area to erase the remnants. Alternatively you could leave out the translate and increment x by interval to move your rect.

    Hacky fix:

    context.clearRect(x+((interval>0)?-.5:.5), y, w, h);