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 = ""; // 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);
body {
  width: 100%;
  height: 100%;
  margin: 0px;
  border: 0;
  overflow: hidden;
  display: block;
<canvas id="c" width="600" height="400"></canvas>

<img style="display: none;" id="the_button" src="" />

<img style="display: none;" id="the_background" src="" />


Source: Ask Javascript Questions