How do I move an image in JavaScript? -


i trying draw , move image using js.

this code works until moveimage function nothing. can me figure out?

i believe can image move if place in html, prefer have script code place 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 img.style.left/right either not correct or not pointing img properly.

if there no way this, there way me remove (not hide) image can redraw in new location?

you have scope issue. defining fps inside interval. needs done before can used on 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 cannot reposition image on canvas. needs redrawn onto canvas.

once call context.drawimage() image can no longer manipulated. have, suggests, drew onto canvas. it's not same html element within dom. coloured pixels on canvas.

see demo: http://jsfiddle.net/8ljvnt8j/1/

however you'll notice image being repeated. because drawing on top of canvas. canvas 2d painting on top of there.

therefore need clear down 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(); 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -