Saving and restoring the context

Best practice: save the context at the beginning of any function
that changes the context, restore it at the end of the function!

  1. function drawMonster(x, y, angle, headColor, eyeColor) {
  2.     // BEST PRACTICE : SAVE CONTEXT AND RESTORE IT AT THE END
  3.     ctx.save();
  4.     // Moves the coordinate system so that the monster is drawn
  5.     // at position (x, y)
  6.     ctx.translate(x, y);
  7.     ctx.rotate(angle);
  8.     // head
  9.     ctx.fillStyle=headColor;
  10.     ctx.fillRect(0,0,200,200);
  11.     // eyes
  12.     ctx.fillStyle=‘red’;
  13.     ctx.fillRect(35,30,20,20);
  14.     ctx.fillRect(140,30,20,20);
  15.     // interior of eye
  16.     ctx.fillStyle=eyeColor;
  17.     ctx.fillRect(43,37,10,10);
  18.     ctx.fillRect(143,37,10,10);
  19.  
  20.     
  21.     // BEST PRACTICE!
  22.     ctx.restore();
  23. }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s