Functions

Functions are the key to building complex programs. Any time that you repeat some code it is probably better to put the code in a function and call it repeatedly. You should use functions as building blocks, make very basic functions such as a circle function. Then you can use circle() to make tires for a truck function. Try not to let your functions get to large, they should do one specific thing.

<!DOCTYPE HTML>
<html>
<head>
<title>Functions</title>
</head>
<body style="margin:0px; overflow:hidden;">
<canvas id="canvas"></canvas>
<script>

var can = document.getElementById("canvas");
var ctx = can.getContext('2d');
var cw = can.width = window.innerWidth;
var ch = can.height = window.innerHeight;

function circle(x, y, radius, color) {
  ctx.beginPath();
  ctx.fillStyle = color;
  ctx.arc(x, y, radius, 0, Math.PI*2);
  ctx.fill();
}

function truck(x, y, color) {
  ctx.fillStyle = color;
  ctx.fillRect(x+20, y-20, 30, 20)
  ctx.fillRect(x, y, 100, 30);
  circle(x+20, y+20, 15, "black");
  circle(x+80, y+20, 15, "black");
}

truck(cw/2-50, ch/2-40, "red");
truck(cw/2-50, ch/2+40, "blue");

</script>
</body>
</html>


Now you should have the main tools you need to create your own games and become a programming master! In the example section there will be a few simple games that you can take a look at. The code is commented pretty well, so it should help you understand what is happening in each function.