Canvas implementation of a horizontal scroll (side-scrolling) map

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.