Game Development Reference
In-Depth Information
To get our brick to the right position, we will translate the context to this point. context.translate(x, y)
moves the coordinate system of the context by x and y. That means once you translated the context by
(10, 10) you would start to draw at (10, 10), with a command like moveTo(0, 0). In our case, we move the
coordinate system of the brick to the desired position of the brick. That means we multiply the column and
row by the BRICK_SIZE and translate with those values. No problem so far. This would work perfectly fine
for the first brick; but if the second brick would also translate the context, it would be translated to a wrong
position since the first one already translated the context to its location. One solution is to translate the
context back, but we would rather introduce you to a more powerful way of doing it.
With context.save() you can save the current status of the context. It actually puts the current status on a
stack. If you then change the context and call context.restore() after that, you return to the same
unchanged status. As mentioned, it actually puts the status on a stack so you can call save(), then change
a few things, and call save() again. If you call restore() once you go on, step back to your last save() call.
By calling restore again you'd be at the starting point.
So in between the save() and the restore() calls, we set our context to the right position. Then just set the
fillColor to black and draw a rectangle. Easy, right?
After the drawing, we go back to the original status of the context by calling context.restore() . That way
the next brick can do the same without knowing where the previous brick was placed.
Circle
Our next brick, the circle, is nearly as easy as the square. As with the square, we create a new circle.js
file within our javascripts/bricks folder and add the <script> tag to our index.html file. The first few
lines of code look very similar to the square code; we just change the type and variable name.
var Circle = function() {
this.row = 0;
this.column = 0;
this.type = "Circle";
this.rotation = 0;
}
Circle.prototype.draw = function(context) {
var radius = BRICK_SIZE / 2;
context.save();
context.translate(this.column * BRICK_SIZE, this.row * BRICK_SIZE);
context.fillColor = 0;
context.beginPath();
context.arc(radius, radius, radius, 0, Math.PI * 2);
context.closePath();
context.fill();
 
Search WWH ::




Custom Search