Book Image

HTML5 Game Development by Example: Beginner's Guide

By : Seng Hin Mak
Book Image

HTML5 Game Development by Example: Beginner's Guide

By: Seng Hin Mak

Overview of this book

Table of Contents (18 chapters)
HTML5 Game Development by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
9
Building a Physics Car Game with Box2D and Canvas
Index

Time for action – putting the circle drawing code into a function


Let's make a function to draw the circle and then draw some circles in the Canvas. We are going to put code in different files to make the code simpler:

  1. Open the untangle.drawing.js file in our code editor and put in the following code:

    if (untangleGame === undefined) {
      var untangleGame = {};
    }
    
    untangleGame.drawCircle = function(x, y, radius) {
      var ctx = untangleGame.ctx;
      ctx.fillStyle = "GOLD";
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, Math.PI*2, true);
      ctx.closePath();
      ctx.fill();
    };
  2. Open the untangle.data.js file and put the following code into it:

    if (untangleGame === undefined) {
      var untangleGame = {};
    }
    
    untangleGame.createRandomCircles = function(width, height) {
      // randomly draw 5 circles
      var circlesCount = 5;
      var circleRadius = 10;
      for (var i=0;i<circlesCount;i++) {
        var x = Math.random()*width;
        var y = Math.random()*height;
        untangleGame.drawCircle(x, y, circleRadius);
      }
    };
  3. Then...