4.3. Drawing a Rectangle
Problem
You want to draw a rectangle at runtime.
Solution
Create a custom MovieClip.drawSimpleRectangle( )
method using the Drawing API and invoke it on a
movie clip.
Discussion
To draw a simple rectangle, specify the stroke’s
attributes
using the lineStyle(
) method and then draw four lines using the
lineTo( ) method:
// Create rectangle_mc with a depth of 1 on the main timeline.
_root.createEmptyMovieClip("rectangle_mc", 1);
// Specify a one-pixel, solid, black line.
rectangle_mc.lineStyle(1, 0x000000, 100);
// Draw four lines to form the perimeter of the rectangle.
rectangle_mc.lineTo(100, 0);
rectangle_mc.lineTo(100, 50);
rectangle_mc.lineTo( 0, 50);
rectangle_mc.lineTo( 0, 0);Thus, drawing a simple rectangle is no huge feat. To draw multiple
rectangles with various dimensions, you should create a custom
drawSimpleRectangle( ) method for the
MovieClip class, as follows:
// Define the custom method on MovieClip.prototype so that it's available to all
// movie clip instances.
MovieClip.prototype.drawSimpleRectangle = function (width, height) {
this.lineTo(width, 0);
this.lineTo(width, height);
this.lineTo(0, height);
this.lineTo(0, 0);
}
// Invoke the custom method like this.
_root.createEmptyMovieClip("rectangle_mc", 1);
rectangle_mc.lineStyle(1, 0x000000, 100);
rectangle_mc.drawSimpleRectangle(100, 50);The dimensions of the rectangle are 102 × 52 pixels due to the line thickness. Reduce the dimensions by two pixels in each direction to create a rectangle ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access