Clearing previous positions of canvas object and not the entire canvas

  canvas, html, javascript

l believe to have a logic error in the way of which my logic is meant to find the previous coordinates of my canvas object, a moving image, and delete the frame drawn before it so that it does not duplicated the image every time it is drawn onto the canvas.

There is a reproducible demo below and l added comments where l believe the problem occurs.

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var the_background = document.getElementById("the_background");

var imgTag = new Image();
var X_POS = canvas.width;
var Y_POS = 0;

imgTag.src = "http://i.stack.imgur.com/Rk0DW.png"; // load image

function animate() {

  /* Error resides from here */
  var coords = {};
  coords.x = Math.floor(this.X_POS - imgTag);
  coords.y = Math.floor(this.Y_POS - imgTag);

  ctx.clearRect(coords.x, coords.y, X_POS, Y_POS);
  /* To here */


  ctx.drawImage(imgTag, X_POS, Y_POS);
  X_POS -= 5;
  if (X_POS > 200) requestAnimationFrame(animate)
}


window.onload = function() {

  ctx.drawImage(the_background, 0, 0, canvas.width, canvas.height);
  animate();
}
html,
body {
  width: 100%;
  height: 100%;
  margin: 0px;
  border: 0;
  overflow: hidden;
  display: block;
}
<html>
<canvas id="c" width="600" height="400"></canvas>

<img style="display: none;" id="the_button" src="https://i.imgur.com/wO7Wc2w.png" />

<img style="display: none;" id="the_background" src="https://img.freepik.com/free-photo/hand-painted-watercolor-background-with-sky-clouds-shape_24972-1095.jpg?size=626&ext=jpg" />

</html>

Source: Ask Javascript Questions

LEAVE A COMMENT