views:

41

answers:

2

Hi,

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.

+2  A: 

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/drawing_graphics_with_canvas

Here is an example of animating on a canvas: https://developer.mozilla.org/en/Canvas_tutorial/Basic_animations

James Black
I thought about it - But If you have loaded 10 images and draw some rectangles on your canvas.And You want to move only one rectangle,You will need to redraw everything again and again at each loop
Yosy
Not really, clear the rectangle of interest and then draw it again. This bit about 10 images would have been nice to know at the beginning, btw.
James Black
+1  A: 

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);
Nick Canzoneri