HTML5 Canvas realizes the movement of characters

Source: Internet
Author: User

Use HTML5 Canvas's DrawImage (img,sx,sy,sw,sh,x,y,w,h) to realize the movement of characters. where IMG is a picture, sx,sy,sw,sh four parameters are optional, when you need to trim the picture, the x, y coordinates to trim from, and the width and height to trim. X,y,w,h is the width and height of the x, Y coordinates drawn in the scene, and the picture that is drawn. When Sw,sh and w,h are inconsistent, the method scales the picture, noting the consistency of the proportions.

The following is the HTML code:

<!DOCTYPE HTML><Head> <MetaCharSet= "Utf-8"> <title>Moving little Ones</title></Head><Body> <Scripttype= "Text/javascript"src= "Js/jquery.js"></Script> <Scripttype= "Text/javascript"src= "Js/main.js"></Script> <Div>  <CanvasID= "Canvas"width= "1000px"Height= "600px"></Canvas> </Div></Body></HTML>

Create a canvas, get to and create a scene in JS:

can = document.getElementById (' canvas '= Can.getcontext (' 2d ');

Refresh the content with SetInterval () and change the coordinates of the plotted person in the DrawImage () method, so that the little man is moving.
We add keyboard events KeyDown () and KeyUp () to determine key values when the keyboard is pressed. The E.which in jquery here is judged by the left button of 37 and the right key to 39.

(function  Keycontrol () {    $ (document). KeyDown(function(e) {        =  E.which;         if (Key ==37) {            = ' left ';             =;        } Else if (Key ==39) {            = ' right ';             = 0;        }    });    $ (document). KeyUp (function(e) {        = ' Stop ';    })}) ();

When the keyboard is pressed, set the direction, clear the direction when releasing, stop moving.

Code Address: Https://github.com/abike/move-person

HTML5 Canvas realizes the movement of characters

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.