API: Transformations

rsandor edited this page Aug 9, 2011 · 4 revisions

How Transformations Work

Gury allows your to register global transformations that will effect each rendered object. Here is a simple example that "shifts" objects down ten pixels and right ten pixels:

$g('screen').size(100, 100)
  // Add a red square at (0, 0)
  .add(function(ctx) {
    ctx.fillStyle = "red";
    ctx.fillRect(0, 0, 10, 10);
  })
  // Add a blue square at (50, 50)
  .add(function(ctx) {
    ctx.fillStyle = "blue";
    ctx.fillRect(50, 20, 10, 10);
  })
  // Add a global translation that shifts them right and down by 10 pixels
  .addTransform({
    up: function(ctx) {
      ctx.save();
      ctx.translate(10, 10);
    },
    down: function(ctx) {
      ctx.restore();
    }
  })
  // Draw and animate...
  .play(16);

In the example we first add a couple of squares and then use the addTransform() method to "shift" everything down and to the right. A transformation object needs to have two methods: an up() method which is run before rendering objects and a down() method which is run after all objects have been rendered.

There are many interesting things you can do with transformations. I added them in because my friends and I needed an easy way to create a camera for a 2D platformer we are working on (we use translations to literally translate the game world's objects to give the illusion of a viewport). We use another transformation to stretch the rendered sprites (using a scale() operation) to give the game a "retro" look and feel.

For more ideas for how to use transformations visit the MDC Canvas Documentation - Transformations page. Happy coding!

Methods

Below are listed the Gury methods that deal with adding, removing, and manipulating transformations.

.addTransform(transformation)

Adds a transformation to the Gury instance. The transformation must be structured like so:

var myTransformation = {
  up: function(ctx, canvas) {
    // Perform operations before rendering objects...
  },
  down: function(ctx, canvas) {
    // Clean up transformation operations here...
  }
};

.removeTransform(transformation)

Removes a global transformation. Note: you will need to provide the exact object to remove the transformation as this feature does not yet support tagging.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.