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