캠핑과 개발

HTML5의 canvas태그를 이용하여 생성된 객체를 튕기는 예제입니다.






전체소스

  1. <!DOCTYPE html>
  2. <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  3. canvas {
  4.     border:1px solid #d3d3d3;
  5.     background-color: #f1f1f1;
  6. }
  7. </head>
  8. <body onload="startGame()">
  9.  
  10. var myGamePiece;
  11.  
  12. function startGame() {
  13.     myGamePiece = new component(30, 30, "red", 80, 75);
  14.     myGameArea.start();
  15. }
  16.  
  17. var myGameArea = {
  18.     canvas : document.createElement("canvas"),
  19.     start : function() {
  20.         this.canvas.width = 480;
  21.         this.canvas.height = 270;
  22.         this.context = this.canvas.getContext("2d");
  23.         document.body.insertBefore(this.canvas, document.body.childNodes[0]);
  24.         this.interval = setInterval(updateGameArea, 20);        
  25.     },
  26.     stop : function() {
  27.         clearInterval(this.interval);
  28.     },    
  29.     clear : function() {
  30.         this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  31.     }
  32. }
  33.  
  34. function component(width, height, color, x, y, type) {
  35.     this.type = type;
  36.     this.width = width;
  37.     this.height = height;
  38.     this.x = x;
  39.     this.y = y;    
  40.     this.speedX = 0;
  41.     this.speedY = 0;    
  42.     this.gravity = 0.1;
  43.     this.gravitySpeed = 0;
  44.     this.bounce = 0.6;
  45.     this.update = function() {
  46.         ctx = myGameArea.context;
  47.         ctx.fillStyle = color;
  48.         ctx.fillRect(this.x, this.y, this.width, this.height);
  49.     }
  50.     this.newPos = function() {
  51.         this.gravitySpeed += this.gravity;
  52.         this.x += this.speedX;
  53.         this.y += this.speedY + this.gravitySpeed;
  54.         this.hitBottom();
  55.     }
  56.     this.hitBottom = function() {
  57.         var rockbottom = myGameArea.canvas.height - this.height;
  58.         if (this.y > rockbottom) {
  59.             this.y = rockbottom;
  60.             this.gravitySpeed = -(this.gravitySpeed * this.bounce);
  61.         }
  62.     }
  63. }
  64.  
  65. function updateGameArea() {
  66.     myGameArea.clear();
  67.     myGamePiece.newPos();
  68.     myGamePiece.update();
  69. }
  70.  
  71.  
  72. <p>The bouncing property indicates how strong a component will bounce back, after hitting the ground.</p>
  73.  
  74. <p>Set the bouncing property to a decimal number between 0 and 1.</p>
  75.  
  76. <p>0 = no bouncing.</p>
  77. <p>1 = will bounce all the way back.</p>
  78.  
  79. </body>
  80. </html>
  81.  


http://www.w3schools.com/games/game_bouncing.asp