Often you'll prefer to move an element on JavaScript's canvas. This process is actually very similar to the rotation mechanism for HTML5 programming. Here's some code that moves an image and wraps it to the other side when it leaves the canvas.
//from wrap.html var drawing; var con; var goofyPic; CANV_HEIGHT = 200; CANV_WIDTH = 200; SPR_HEIGHT = 50; SPR_WIDTH = 40; var x = 0; var y = 100; var dx = 10; var dy = 7; function init(){ drawing = document.getElementById("drawing"); con = drawing.getContext("2d"); goofyPic = document.getElementById("goofyPic"); setInterval(draw, 100); } function draw(){ //clear background con.clearRect(0, 0, 200, 200); //move the element x += dx; y += dy; //check for boundaries wrap(); //draw the image con.drawImage(goofyPic, x, y, SPR_WIDTH, SPR_HEIGHT); //draw a rectangle con.strokeStyle = "red"; con.lineWidth = 5; con.strokeRect(0, 0, CANV_WIDTH, CANV_HEIGHT); } // end draw function wrap(){ if (x > CANV_WIDTH){ x = 0; } if (x < 0){ x = CANV_WIDTH; } if (y > CANV_HEIGHT){ y = 0; } // end if if (y < 0){ y = CANV_HEIGHT; } } // end wrap
The wrap code is very similar to the rotation program. It has a few different features. Here's what it does:
Keeps track of the sprite position.
The sprite's position will change now, so the important variables are X and Y, used to track where the sprite is.
Contains variables for the sprite's motion.
The dx variable stands for difference in x, and it is used to show how much the x value changes each frame. Likewise, dy is used to show how much the y value changes in each frame. x, y, dx, and dy are all created outside the function context.
Moves the element values.
In every frame (in the draw() function), add dx to x and add dy to y.
Checks for boundaries.
Here, a new function called wrap() was created to check for boundary conditions.
The code is pretty straightforward. If the sprite's x value exceeds the width of the canvas (meaning it has moved to the right border of the canvas), reset the x value to 0 (moving it to the left). Use a similar calculation to check the other borders and reset the image to the opposite side.