I'm adding a line to a canvas using canvas.moveTo(0, 0); canvas.lineTo(100, 100);
, but I then want the user to move the mouse to set the rotation of the line. Google suggests using the rotation
property, but I don't have a reference to the line object. Can I get a reference to the line or should I rotate the whole canvas? Is any of this possible?
views:
766answers:
3Hmmm... Add a Sprite to the canvas, then draw the line onto the graphics object of the Sprite. Then you can rotate the Sprite etc. You can rotate the canvas if you wanted to, but it's extra overhead to create a canvas if you're only going to treat it as a Sprite (Note that Canvas extends Sprite somewhere down the chain).
Take a look at this example from the ASDocs: Rotating things
Typically you manipulate the surface onto which the graphics are drawn -- usually a Sprite instance, since it's so lightweight and well suited to the task. If instead you created a new Sprite, used its Graphics object to draw your lines, shapes, etc., added the Sprite to a UIComponent -- you can't add a Sprite to a Canvas directly without wrapping it first in a UIComponent instance -- then added that UIComponent to your Canvas, you could manipulate the Sprite directly via rotation, movement, etc.
That's generally how it's done, either by overriding createChildren() (if the object's intended to live for the duration of your component instance) or using some other method, depending on your needs. For example:
override protected function createChildren():void
{
super.createChildren();
// Create a new Sprite and draw onto it
var s:Sprite = new Sprite();
s.graphics.beginFill(0, 1);
s.graphics.drawRect(0, 0, 20, 20);
s.graphics.endFill();
// Wrap the Sprite in a UIComponent
var c:UIComponent = new UIComponent();
c.addChild(s);
// Rotate the Sprite (or UIComponent, whichever your preference)
s.rotation = 45;
// Add the containing component to the display list
this.addChild(c);
}
Hope it helps!
What is canvas (an actual Canvas does not have a lineTo() or a moveTo() method)?
Seems like you are probably manipulating the graphics object of the Canvas. In which case you'd be better doing the following
private var sp : Sprite;
//canvas is whatever Canvas you wish to add the sprite to
private function addLine(canvas : Canvas) : void {
sp = new Sprite();
/* Do the drawing of the sprite here,
such as sp.graphics.moveTo or sp.graphics.lineTo */
sp.rotation = 45;
canvas.rawChildren.addChild(sp);
}
Then whenever you wish to change the rotation just update sp.rotation (which is now in your canvas)