Yosi
Yosi

Reputation: 2976

Canvas - Getting Image Position

I am using canvas,and I have this code -

        var myCanvas = document.getElementById("myCanvas"),
        ctx = null;

    // Check for support - Feature Support and not Browser Support
    if ( myCanvas.getContext) {
        // Getting the context future 3d ^_^
        ctx = myCanvas.getContext("2d");

        var googleLogo = new Image();
        googleLogo.src = 'img.png';
        googleLogo.onload = function(){
            // Adding our image..
            ctx.drawImage(googleLogo,0,0); // drawImage(image object,x,y)
        };

        }else{
        alert("You don`t have support in CANVAS !");
    }

I want to make this an animation to make google logo move from (0,0) to (0,120).
Theoretically I know that I need to use setInterval and every x seconds I need to increase the y of my image,but how I can change the y position of my image?

                    setInterval(function(){
                    var imgY = ?; // How I can get my image y?or x?
                    if(imgY != 120){
                        imgY += 2;   // adding the velocity
                    }

                },250);

Thanks,Yosy.

Upvotes: 1

Views: 7804

Answers (2)

James Black
James Black

Reputation: 41848

Why not just clear the canvas, then draw the image, having shifted your y coordinate.

Or you can use translate, this page gives an example: https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_Graphics_with_Canvas

Here is an example of animating on a canvas: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Basic_animations

Upvotes: 3

Nick Canzoneri
Nick Canzoneri

Reputation: 3804

You can use a recursive function like:

 function iterate(dy){
    if(dy < 120){
      setTimeout(function(){
        ctx.clearRect(0,0,500,500);
        ctx.drawImage(googleLogo,0,dy);
        iterate(dy+1);  
      },50);
    }
  }
  iterate(0);

Upvotes: 2

Related Questions