Advertisement
Guest User

Untitled

a guest
May 17th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  5. <style>
  6. canvas {
  7. border:5px solid #d3d3d3;
  8. background-color: #f1f1f1;
  9. }
  10.  
  11.  
  12.  
  13. </style>
  14. </head>
  15. <body onload="startGame()">
  16. <script>
  17.  
  18. var myGamePiece;
  19.  
  20. function startGame() {
  21. myGameArea.start();
  22. myGamePiece = new component(100, 100, "black", 100, 100);
  23. }
  24.  
  25. var myGameArea = {
  26. canvas : document.createElement("canvas"),
  27. start : function() {
  28. this.canvas.width = 500;
  29. this.canvas.height = 500;
  30. this.context = this.canvas.getContext("2d");
  31. document.body.insertBefore(this.canvas, document.body.childNodes[0]);
  32. this.interval = setInterval(updateGameArea, 20);
  33. window.addEventListener('keydown', function (e) {
  34. myGameArea.key = e.keyCode;
  35. })
  36. window.addEventListener('keyup', function (e) {
  37. myGameArea.key = false;
  38. })
  39. },
  40. clear : function(){
  41. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  42. }
  43. }
  44.  
  45. function component(width, height, color, x, y) {
  46. this.gamearea = myGameArea;
  47. this.width = width;
  48. this.height = height;
  49. this.speedX = 0;
  50. this.speedY = 0;
  51. this.x = x;
  52. this.y = y;
  53. this.update = function() {
  54. ctx = myGameArea.context;
  55. ctx.fillStyle = color;
  56. ctx.fillRect(this.x, this.y, this.width, this.height);
  57. }
  58. this.newPos = function() {
  59. this.x += this.speedX;
  60. if(this.x<0) this.x = 0;
  61. if(this.x > 500 - this.width) this.x = 500 - this.width;
  62. this.y += this.speedY;
  63. if (this.y<0) this.x = 0;
  64. if(this.y > 500 - this.width) this.y = 500 - this.width;
  65. }
  66. }
  67.  
  68. function updateGameArea() {
  69. myGameArea.clear();
  70. myGamePiece.speedX = 0;
  71. myGamePiece.speedY = 0;
  72. if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -1; }
  73. if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 1; }
  74. if (myGameArea.key && myGameArea.key == 38) {myGamePiece.speedY = -1; }
  75. if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }
  76. myGamePiece.newPos();
  77. myGamePiece.update();
  78. }
  79. </script>
  80. </body>
  81. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement