캠핑과 개발

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.frameNo = 0;
  25.         this.interval = setInterval(updateGameArea, 20);
  26.     },
  27.     stop : function() {
  28.         clearInterval(this.interval);
  29.     },    
  30.     clear : function() {
  31.         this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  32.     }
  33. }
  34.  
  35. function component(width, height, color, x, y) {
  36.     this.width = width;
  37.     this.height = height;
  38.     this.angle = 0;
  39.     this.x = x;
  40.     this.y = y;    
  41.     this.update = function() {
  42.         ctx = myGameArea.context;
  43.         ctx.save();
  44.         ctx.translate(this.x, this.y);        
  45.         ctx.rotate(this.angle);
  46.         ctx.fillStyle = color;
  47.         ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);        
  48.         ctx.restore();    
  49.     }
  50. }
  51.  
  52. function updateGameArea() {
  53.     myGameArea.clear();
  54.     myGamePiece.angle += 1 * Math.PI / 180;    
  55.     myGamePiece.update();
  56. }
  57.  
  58.  
  59. <p>The red square will rotate one degree every time the gamearea updates (50 times per second).</p>
  60.  
  61. <p>Note: The angle property must be a radian. You can convert degrees into radians by using the formula x * Math.PI / 180</p>
  62. </body>
  63. </html>
  64.  


출처 :

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