Advertisement
here2share

HTML_Graphics_ArrowKeys

Apr 29th, 2015
365
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.69 KB | None | 0 0
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  3. <head>
  4. <!-- AdFender script begin --><script type='text/javascript' src='http://local.adfender.com/adfender/elemhide.js'></script><!-- AdFender script end -->
  5.     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
  6.     <title>Basic HTML5 Game Demo</title>
  7. </head>
  8. <body>
  9.     <canvas id="canvas"></canvas>
  10.     <script type="text/javascript">
  11.         var canvas = document.getElementById('canvas');
  12.         var ctx = canvas.getContext('2d');
  13.          
  14.         canvas.width = 800;
  15.         canvas.height = 600;
  16.  
  17.         var mySprite = {
  18.             x: 200,
  19.             y: 200,
  20.             width: 50,
  21.             height: 50,
  22.             speed: 200,
  23.             color: '#c00'
  24.         };
  25.  
  26.         var keysDown = {};
  27.         window.addEventListener('keydown', function(e) {
  28.             keysDown[e.keyCode] = true;
  29.         });
  30.         window.addEventListener('keyup', function(e) {
  31.             delete keysDown[e.keyCode];
  32.         });
  33.  
  34.         function update(mod) {
  35.             if (37 in keysDown) {
  36.                 mySprite.x -= mySprite.speed * mod;
  37.             }
  38.             if (38 in keysDown) {
  39.                 mySprite.y -= mySprite.speed * mod;
  40.             }
  41.             if (39 in keysDown) {
  42.                 mySprite.x += mySprite.speed * mod;
  43.             }
  44.             if (40 in keysDown) {
  45.                 mySprite.y += mySprite.speed * mod;
  46.             }
  47.         }
  48.  
  49.         function render() {
  50.             ctx.fillStyle = '#000';
  51.             ctx.fillRect(0, 0, canvas.width, canvas.height);
  52.             ctx.fillStyle = mySprite.color;
  53.             ctx.fillRect(mySprite.x, mySprite.y, mySprite.width, mySprite.height);
  54.         }
  55.  
  56.         function run() {
  57.             update((Date.now() - time) / 1000);
  58.             render();
  59.             time = Date.now();
  60.         }
  61.  
  62.         var time = Date.now();
  63.         setInterval(run, 10);
  64.  
  65.     </script>
  66. </body>
  67. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement