The title is a bit of a fuss, in fact, to achieve a seemingly continuous movement of the background picture. The effect is as follows:
Implementation principle:
Picture 1 and Picture 2 is a two-way picture, image 1 to move out of the canvas at a certain speed, picture 2 slowly moved into the canvas, when the picture 1 completely moved out of the canvas range, immediately reset the picture 1 position, because the two images are the end-to-end cohesion, so it looks like an infinite scrolling map.
Key code:
1 varc = document.getElementById (' C '),//Canvas2CTX = Canvas.getcontext (' 2d '),3IMG =NewImage (),4Offset = 0,5FPS = 60,6Speed = 80/fps;//speed per frame7 8IMG.SRC = "Test.jpg";9 Ten functionDraw (CTX) { One Ctx.save (); A //Offset < c.width? (offset + speed): 0 - //The latter cannot be simply reset to 0, because the speed is too fast offset may exceed the size of the canvas - //Therefore, we need to calculate the difference between the two theOffset = Offset < c.width? (offset + speed): (Offset-c.width); - //Scroll through translate to achieve the picture -Ctx.translate (-offset, 0); - + //just draw the picture properly on the screen and don't need to manipulate its position -Ctx.drawimage (IMG, 0, 0); +Ctx.drawimage (img,img.width,0); A Ctx.restore (); at } -Window.onload =function() { -(function() { -Ctx.clearrect (0, 0, C.width, c.height); - Draw (CTX); - Requestanimationframe (arguments.callee,c); in })(); -};
View Code
Canvas implementation of a horizontal scroll (side-scrolling) map