1 /**
  2  * Copyright (C) 2009-2011 Klaus Reimer <k@ailis.de>
  3  * See LICENSE.txt for licensing information.
  4  * 
  5  * @require twodee.js
  6  * @require twodee/SceneNode.js
  7  */
  8 
  9 /**
 10  * Constructs a new image node.
 11  * 
 12  * @param {HTMLImageElement|Image} image
 13  *            Optional image. If not set then it must be set with the
 14  *            setImage() method.
 15  *            
 16  * @constructor
 17  * @extends {twodee.SceneNode}
 18  * @class
 19  * A node which draws an image.
 20  */
 21 twodee.ImageNode = function(image)
 22 {
 23     twodee.SceneNode.call(this);
 24     if (image) this.setImage(image);
 25     twodee.ImageNode.counter++;
 26 };
 27 twodee.inherit(twodee.ImageNode, twodee.SceneNode);
 28 
 29 /** 
 30  * Instance counter.
 31  * 
 32  * @private
 33  * @type {number}
 34  */
 35 twodee.ImageNode.counter = 0; 
 36 
 37 /**
 38  * The image.
 39  * 
 40  * @private
 41  * @type {HTMLImageElement|Image}
 42  */
 43 twodee.ImageNode.prototype.image = null;
 44 
 45 /** 
 46  * If bounds should be drawn (For debugging).
 47  * 
 48  * @private
 49  * @type {boolean}
 50  */
 51 twodee.ImageNode.prototype.showBounds = false;
 52 
 53 /**
 54  * Sets the image
 55  * 
 56  * @param {HTMLImageElement|Image} image
 57  *            The image to set
 58  */
 59 twodee.ImageNode.prototype.setImage = function(image)
 60 {
 61     this.image = image;
 62 };
 63 
 64 /**
 65  * Returns the image.
 66  * 
 67  * @return {HTMLImageElement|Image} The image
 68  */
 69 twodee.ImageNode.prototype.getImage = function()
 70 {
 71     return this.image;
 72 };
 73 
 74 /**
 75  * Enables or disables the display of node bounds. This is for debugging
 76  * purposes.
 77  * 
 78  * @param {boolean} showBounds
 79  *            True to show the bounds, false to hide them
 80  */
 81 twodee.ImageNode.prototype.setShowBounds = function(showBounds)
 82 {
 83     this.showBounds = showBounds;
 84 };
 85 
 86 /**
 87  * @see twodee.SceneNode#render
 88  * 
 89  * @param {CanvasRenderingContext2D} g
 90  *            The graphics context
 91  * @param {twodee.Matrix} transform
 92  *            The transformation
 93  * @override
 94  */
 95 twodee.ImageNode.prototype.render = function(g, transform)
 96 {   
 97     var width, height, img, bounds;
 98     
 99     img = this.image;
100     
101     if (!img) return;
102     width = img.width;
103     height = img.height;
104     if (!width || !height) return;
105     
106     g.save();
107     g.transform(transform.m00, transform.m10, transform.m01, transform.m11,
108         transform.m02, transform.m12);
109     g.drawImage(img, -width / 2, -height / 2);
110     g.restore();
111 
112     if (this.showBounds)
113     {
114         bounds = this.getBounds();
115         if (bounds)
116         {
117             bounds.apply(g);
118             g.strokeStyle = "red";
119             g.stroke();
120         }
121     }
122 };
123