ctx.lineTo() method - Anomalous behavior after canvas clearance

It is observed that when a shape is drawn at progressively shifting positions, previously drawn shapes too get displayed along with the current one, despite having cleared the canvas prior to each such action.

It is not as if ctx.clearRect() function is not doing its job. It does successfully clear the canvas, but as soon as the code block for drawing the shape gets executed next time, shapes pertaining to older positions too come up simultaneously. Such behavior seems anomalous.

I would be thankful if members of this forum could kindly look into the matter and provide their valuable insight.

Sample JavaScript code used for testing the phenomenon is placed below:

var canv = document.getElementById("myCanvas");
var ctx = canv.getContext("2d");
var x = 0;

window.addEventListener("load", shapeMovementTest, false);

function shapeMovementTest() {
  // Set time interval to 40 ms (for 25 frames per sec)
  var timer = setInterval(function () {
    // Clear canvas
    ctx.clearRect(0, 0, canv.width, canv.height);
    ctx.moveTo(x, 150);
    ctx.lineTo(x + 30, 150);
    ctx.lineTo(x + 30, 120);

    if (x < canv.width - 30) {
      x = x + 5;
    } else {
  }, 40);

Hello there,

Simple typo :slightly_smiling_face:

If you want to know why, take a look at the first note on this page:

Hope this helps.

My sincere thanks Shaun !

As rightly pointed out by you, missing parenthesis at the end of ctx.beginPath(); statement was the culprit.

I am still wondering how I kept missing it, even while looking at the code repeatedly.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.