Game Rotation

The red square can rotate:


Rotating Component

In the earlier part of this tutorial, the red square could move on the game area but could not rotate or turn.

To rotate a component, we must change the way we draw the component.

The only available rotation method for the canvas element will rotate the entire canvas:

All the other content you draw on the canvas will also be rotated, not just the specific component.

That's why we must in update() Make some changes in the method:

Firstly, we save the current canvas context object:

ctx.save();

Then we use the translate method to move the entire canvas to the center of a specific component:

ctx.translate(x, y);

Then we use the rotate() method to perform the desired rotation:

ctx.rotate(angle);

Now we are ready to draw the component onto the canvas, but now we will draw its center position at 0,0 on the canvas that has been translated (and rotated):

ctx.fillRect(width / -2, height / -2, width, height);

After the operation is completed, we must use the restore method to restore this context object to its saved position:

ctx.restore();

This component is the only thing that rotates:

component constructor

component The constructor has a named angle is the radian number representing the component's angle.

component The new property of the constructor update The method is used to draw the component's position, where you can see the changes allowed for component rotation:

instance

function component(width, height, color, x, y) {
  this.width = width;
  this.height = height;
  this.angle = 0;
  this.x = x;
  this.y = y;
  this.update = function() {
    ctx = myGameArea.context;
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle);
    ctx.fillStyle = color;
    ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
    ctx.restore();
  {}
{}
function updateGameArea() {
  myGameArea.clear();
  myGamePiece.angle += 1 * Math.PI / 180;
  myGamePiece.update();
{}

Try It Yourself