Adding a Canvas Viewport

SVG made the engine’s life easy to add in a camera; the built-in viewport attribute enables you to control the viewport of the SVG element and act as a camera on the action.

With the Canvas tag’s transforms, however, this functionality can easily be added to a stage using a component you can call viewport. The viewport component can have a few methods to allow a game to adjust the center of the viewport as well as add a sprite to follow, which means to center on the screen at all times.

This component ties into the step event to update the viewport position and then the predraw and draw events to wrap all the rendering calls in the appropriate saves, transforms, and restores based on the state of the viewport.

Add the code for the viewport from Listing 16-6 to the bottom of the quintus_anim.js file before the final closing curly brace.

Listing 16-6: The viewport component

 Q.register('viewport',{ added: function() { this.entity.bind('predraw',this,'predraw'); this.entity.bind('draw',this,'postdraw'); this.x = 0, this.y = 0; this.centerX = Q.width/2; this.centerY = Q.height/2; this.scale = 1; }, extend: { follow: function(sprite) { this.unbind('step',this.viewport); this.viewport.following = sprite; this.bind('step',this.viewport,'follow'); this.viewport.follow(); }, unfollow: function() { this.unbind('step',this.viewport); }, centerOn: function(x,y) { this.viewport.centerOn(x,y); } }, follow: function() { this.centerOn(this.following.p.x + this.following.p.w/2, ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.