How do I move an image in JavaScript?

560 Views Asked by At

I am trying to draw and move an image using JS.

This code works up until the moveImage function which simply does nothing. Can anyone help me figure this out?

I believe that I can get the image to move if I place it in the html, but I would prefer to have the script code place it instead if possible.

function init() {
  var x = 1, y = 1;

  var context = document.getElementById("Vehicle").getContext("2d");
  var img = new Image();
  img.onload = function () { context.drawImage(img, x, y, 24, 20); }
  img.src = "images/Image.png";

  //move
  function moveImage(imgX, imgY) { 
    img.style.left = imgX + "px";
    img.style.top = imgY + 'px';
  }

  setInterval(function () {
    var FPS = 60;
    x++;
    y++;
    if (x > 1000) { x = 1; }
    if (y > 1000) { y = 1; }
    moveImage(x, y);
  }, 1000/FPS);
};

My guess is that img.style.left/right is either not correct or that I am not pointing to img properly.

If there is no way to do this, is there a way for me to remove (not just hide) the image so I can redraw it in the new location?

1

There are 1 best solutions below

8
On BEST ANSWER

You have a scope issue. You are defining FPS inside the interval. This needs to be done before so that it can be used on the interval step parameter.

var FPS = 60;
var timer = (1000/FPS);

setInterval(function () {
    x++;
    y++;
    if (x > 1000) { x = 1; }
    if (y > 1000) { y = 1; }
    moveImage(x, y);
  }, timer);

Furthermore you cannot simply reposition an image on a canvas. It needs to be redrawn onto the canvas.

Once you call context.drawImage() the image can no longer be manipulated. You have, as it suggests, drew this onto the canvas. It's not the same as a HTML element within the DOM. It is now simply coloured pixels on a canvas.

See Demo: http://jsfiddle.net/8Ljvnt8j/1/

However you'll notice that the image is being repeated. This is because you are drawing on top of canvas. The canvas is 2d so you are simply painting on top of what is already there.

Therefore you need to clear down the canvas.

img.onload = function () { 
   context.clearRect(0, 0, canvas.width, canvas.height);
   context.drawImage(img, imgX, imgY, 24, 20);
}

See Demo: http://jsfiddle.net/8Ljvnt8j/2/


All in all:

function init() {

    var x = 1;
    var y = 1;

    var canvas = document.getElementById("Vehicle");

    drawImage();

  //move
  function drawImage() {       
      var context = document.getElementById("Vehicle").getContext("2d");
      var img = new Image();
      img.onload = function () { 
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.drawImage(img, x, y, 24, 20);
  }
  img.src = "https://placeholdit.imgix.net/~text?txtsize=5&txt=20%C3%9720&w=20&h=20";

  }

  var FPS = 60;
   var timer = (1000/FPS);

setInterval(function () {
    x++;
    y++;
    if (x > 1000) { x = 1; }
    if (y > 1000) { y = 1; }
    drawImage();
  }, timer);
};

init();