Create a Basic Drawing Application in Flash

Create a Basic Drawing Application in Flash

Tutorial Details
  • Platform: Flash
  • Language: AS3
  • Libraries used: as3corelib

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This tutorial was first published in August, 2009.

In this tutorial, we’ll create a Drawing Application with basic functions and an easy to use interface. Feeling artistic? Then let’s go..


Step 1: Overview

This application will feature a series of tools such as pencil, eraser, text tool, and also the possibility to save your drawing in png format using the Adobe’s PNG Encoder.


Step 2: Setting Up

Open Flash and create a new Flash File (ActionScript 3).

Set the stage size to 600x350px and the frame rate to 25fps.

””

Step 3: Board

Draw a 600x290px white rectangle and convert it to MovieClip. Set its instance name to "board" and align it to the top-left of the stage.

This will be the area on which we’ll be able to draw.


Step 4: Tools Panel

Create a 600px wide 60px high gray (#DFDFDF) rectangle and align it to the bottom of the stage. This will be our background for the Tools Panel.


Step 5: Tool Icons

I’m not going to cover the creation of the tools icons since that isn’t the intention of the turorial, still, you can see how they are made in the Fla file included in the Source.

As you can see in the image, we’re going to use two icons, one in a gray tone and the other one in color.

Convert the gray pencil icon to a Button (F8) and name it "pencilTool", double click to edit it and add a KeyFrame (F6) in the "over" state. Here’s where we’re going to put the color version of the icon.

Lastly, add another KeyFrame in the "hit" state, and draw a 30x30px square to act as the button’s hit area.

Repeat this process with all your tool icons, don’t forget to give them the correct instance names (eraserTool, textTool, saveButton, clearTool).

In order to display the active tool icon, we’re going to use the color version of the icon and place it in the same position of the button we created before. The instance names will be "pencil", "eraser" and "text".

We’ll hide these icons later using ActionScript.


Step 6: Save Dialog

When we use the save option we’re going to display a "save successful" message.

Create a 600x350px black rectangle with 50% alpha to use as a background.

Add a black rounded rectangle in the center with the save button icon and some text indicating that the save has been completed.

Create a close button and align it in the top-left of the rounded rectangle, name it "closeBtn". As you can imagine, this button will close the Save Dialog.

Convert all the elements to a single MovieClip and mark the "Export for ActionScript" checkbox. Set the Class textfield to "SaveDialog".

We’ll instantiate this class when the user presses the SaveButton and the save is completed.


Step 7: Size Panel

The Size Panel is the area where you can change the size of the pencil, eraser and text tool. You can do that by clicking in the panel area or the oval inside it.

Select the Rectangle Primitive Tool, set the corner radius to 4 and create a #EFEFEF 80x50px rectangle. Convert it to a MovieClip and name it "sizePanel".

Open the Filters panel and add a Drop Shadow with the following values:

Now use the Oval Tool to create a 5x5px black circle and center it in the Size Panel, convert it to MovieClip and set its instance name to "shapeSize".


Step 8: Default Colors

We’ll create a default color palette instead of using the Color Picker Component.

Create a 22x22px circle using the Oval Tool, set its color to #EEEEEE and convert it to MovieClip. Add the same Drop Shadow Filter we used in the Size Panel.

Draw a second circle of 16x16px and use black for the color this time. Center the circles and repeat this process changing the last circle color to the following:

Align them to end up with something like this:

Convert all the colors to a single MovieClip, name it "colors" and be sure to set the Registration Point to the Top-Left, since we’re going to get pixel data using the Bitmap Class.


Step 9: Adobe PNG Encoder

In order to use the Save function we’ll need the Adobe PNG Encoder wich is part of the as3corelib that you can find in Google Code.

To use this class outside of the package it comes with as default, we need to change one line. Open the PNGEncoder.as file and change the line "package com.adobe…" to just "package". This will let us call the class in the directory where the Fla file is.


Step 10: Main Class

A single Class will handle this application. Open the Properties Panel in the Fla file and set the Document Class as "Main".

Create a new ActionScript Document and save it as "Main.as" in the same directory where the Fla file is.


Step 11: Import Required Classes

These are the classes we’re going to need in this app. Remember to check the Flash Help (F1) if you’re unsure of a specific class.

package 
{
	import PNGEncoder;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.DisplayObject;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFieldType;
	import flash.text.TextFieldAutoSize;
	import flash.display.BitmapData;
	import flash.geom.ColorTransform;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import flash.utils.ByteArray;
	import flash.net.FileReference;

Step 12: Extending the Class

We’re extending the MovieClip class since we use this class’ specific properties and methods.

public class Main extends MovieClip
{

Step 13: Variables

These are the variables we’ll use. They’re all explained in the code comments.

/* Pencil Tool shape, everything drawn with this tool and the eraser tool is stored inside board.pencilDraw */

var pencilDraw:Shape = new Shape();

/* Text format */

var textformat:TextFormat = new TextFormat();

/* Colors */

var colorsBmd:BitmapData; //We'll use this Bitmap Data to get the pixel RGB Value when clicked
var pixelValue:uint;
var activeColor:uint = 0x000000; //This is the current color in use, displayed by the shapeSize MC

/* Save dialog instance */

var saveDialog:SaveDialog;

/* Active var, to check which tool is active */

var active:String;

/* Shape size color */

var ct:ColorTransform = new ColorTransform();

Step 14: Main Function

The main function will take care of setting the Text Format of the Text Tool, converting the Colors MovieClip to Bitmap Data so we can extract the Pixels RGB Value, adding the listeners and hiding the active icons.

public function Main():void
{
	textformat.font = "Quicksand Bold Regular"; // You can use any font you like
	textformat.bold = true;
	textformat.size = 16;

   /* We create these functions later */

	convertToBMD();

	addListeners();

	/* Hide tools highlights */

	pencil.visible = false;
	hideTools(eraser, txt);
}

Step 15: Tools Actions

The tools actions are each split into four functions.

The first one will set the tool to its Active state, the second and third ones will handle the Mouse Events (like Drawing or Erasing) and the fourth one will stop those Events.


Step 16: Pencil Tool

These functions handle the Pencil Tool, read the comments in the code for a better understanding.

The set to active function:

private function PencilTool(e:MouseEvent):void
{
	/* Quit active tool */

	quitActiveTool(); //This function will be created later

	/* Set to Active */

	active = "Pencil"; //Sets the active variable to "Pencil"

	/* Adds the listeners to the board MovieClip, to draw just in it */

	board.addEventListener(MouseEvent.MOUSE_DOWN, startPencilTool);
	board.addEventListener(MouseEvent.MOUSE_UP, stopPencilTool);

	/* Highlight, sets the Pencil Tool Icon to the color version, and hides any other tool */

	highlightTool(pencil);
	hideTools(eraser, txt);

   /* Sets the active color variable based on the Color Transform value and uses that color for the shapeSize MovieClip */

	ct.color = activeColor;
	shapeSize.transform.colorTransform = ct;
}

The Start function; this function is called when the Board MovieClip is pressed.

private function startPencilTool(e:MouseEvent):void
{
	pencilDraw = new Shape(); //We add a new shape to draw always in top (in case of text, or eraser drawings)
	board.addChild(pencilDraw); //Add that shape to the board MovieClip

	pencilDraw.graphics.moveTo(mouseX, mouseY); //Moves the Drawing Position to the Mouse Position
	pencilDraw.graphics.lineStyle(shapeSize.width, activeColor);//Sets the line thickness to the ShapeSize MovieClip size and sets its color to the current active color

	board.addEventListener(MouseEvent.MOUSE_MOVE, drawPencilTool); //Adds a listener to the next function
}

The Draw function; called when the user presses the Board MovieClip and moves the mouse.

private function drawPencilTool(e:MouseEvent):void
{
	pencilDraw.graphics.lineTo(mouseX, mouseY); //Draws a line from the current Mouse position to the moved Mouse position
}

Stop function, executed when the user releases the mouse.

private function stopPencilTool(e:MouseEvent):void
{
	board.removeEventListener(MouseEvent.MOUSE_MOVE, drawPencilTool); //Stops the drawing
}

Step 17: Eraser Tool

The Eraser Tool is pretty much the same as the Pencil Tool, except that we don’t use any color other than White.

private function EraserTool(e:MouseEvent):void
{
	/* Quit active tool */

	quitActiveTool();

	/* Set to Active */

	active = "Eraser";

	/* Listeners */

	board.addEventListener(MouseEvent.MOUSE_DOWN, startEraserTool);
	board.addEventListener(MouseEvent.MOUSE_UP, stopEraserTool);

	/* Highlight */

	highlightTool(eraser);
	hideTools(pencil, txt);

   /* Use White Color */

	ct.color = 0x000000;

	shapeSize.transform.colorTransform = ct;
}

private function startEraserTool(e:MouseEvent):void
{
	pencilDraw = new Shape();
	board.addChild(pencilDraw);

	pencilDraw.graphics.moveTo(mouseX, mouseY);
	pencilDraw.graphics.lineStyle(shapeSize.width, 0xFFFFFF); //White Color

	board.addEventListener(MouseEvent.MOUSE_MOVE, drawEraserTool);
}

private function drawEraserTool(e:MouseEvent):void
{
	pencilDraw.graphics.lineTo(mouseX, mouseY);
}

function stopEraserTool(e:MouseEvent):void
{
	board.removeEventListener(MouseEvent.MOUSE_MOVE, drawEraserTool);

}   

As you can see, the code is the same except for the White color changes.


Step 18: Text Tool

The Text Tool has only two functions; one in charge of setting it to active, and the other one for handling the text writing. Let’s take a look:

private function TextTool(e:MouseEvent):void
{
	/* Quit active tool */

	quitActiveTool();

	/* Set to Active */

	active = "Text";

	/* Listener */

	board.addEventListener(MouseEvent.MOUSE_UP, writeText);

	/* Highlight */

	highlightTool(txt);
	hideTools(pencil, eraser);
}

private function writeText(e:MouseEvent):void
{
   /* Create a new TextField Object, this way we won't replace older instances */

	var textfield = new TextField();

	/* Set Formats, position, and focus */

	textfield.type = TextFieldType.INPUT;
	textfield.autoSize = TextFieldAutoSize.LEFT;
	textfield.defaultTextFormat = textformat;
	textfield.textColor = activeColor;
	textfield.x = mouseX;
	textfield.y = mouseY;
	stage.focus = textfield;

	/* Add text to Board */

	board.addChild(textfield);
}

This one was easy, remember that you can change the size and color using the shapeSize and the Colors MovieClips.


Step 19: Save Option

The save option handled by the saveButton will make use of the Adobe’s PNGEnconder Class to save the artwork as a PNG file.

private function export():void
{
	var bmd:BitmapData = new BitmapData(600, 290);//Creates a new BitmapData with the board size

	bmd.draw(board);//Draws the board MovieClip into a BitmapImage in the BitmapData

	var ba:ByteArray = PNGEncoder.encode(bmd); //Creates a ByteArray of the BitmapData, encoded as PNG

	var file:FileReference = new FileReference(); // Instantiates a new File Reference Object to handle the save

	file.addEventListener(Event.COMPLETE, saveSuccessful); //Adds a new listener to listen when the save is complete

	file.save(ba, "MyDrawing.png"); //Saves the ByteArray as a PNG
}

private function saveSuccessful(e:Event):void
{
	saveDialog = new SaveDialog();// Instantiates a new SaveDialog Class

	addChild(saveDialog); //Adds the SaveDialog MovieClip to the Stage

	saveDialog.closeBtn.addEventListener(MouseEvent.MOUSE_UP, closeSaveDialog);//Adds a listener to the close button of the dialog
}

private function closeSaveDialog(e:MouseEvent):void
{
	removeChild(saveDialog); //Removes the dialog of the Stage
}

private function save(e:MouseEvent):void
{
	export(); //Calls the export function to begin the saving process
}

Step 20: Clear Tool

The Clear Tool will add a white screen in front of all the elements in order to leave the board ready to draw again.

private function clearBoard(e:MouseEvent):void
{
	/* Create a white rectangle on top of everything */

	var blank:Shape = new Shape();

	blank.graphics.beginFill(0xFFFFFF);
	blank.graphics.drawRect(0, 0, board.width, board.height);
	blank.graphics.endFill();

	board.addChild(blank);
}

Step 21: Get Colors Value

To get the value of the colors we’re using in the Colors MovieClip, we convert it to a BitmapData Object and use the getPixel method to obtain the RGB value of the pixel clicked.

private function convertToBMD():void
{
	colorsBmd = new BitmapData(colors.width,colors.height);
	colorsBmd.draw(colors);
}

private function chooseColor(e:MouseEvent):void
{
	pixelValue = colorsBmd.getPixel(colors.mouseX,colors.mouseY);//Gets the cliked pixel RGB value
	activeColor = pixelValue;

  /* Use a ColorTransform object to change the shapeSize MovieClip color */

	ct.color = activeColor;
	shapeSize.transform.colorTransform = ct;
}

We’ll add the chooseColor listener in the addListeners function later in the code.


Step 22: Active Tool

Earlier, we declared a variable to set the active or current tool in use, and we call this function to remove the corresponding listeners in order to have just one active tool.

Basically, the function checks the "active" variable in a switch loop, then depending on its value removes the listeners it has.

private function quitActiveTool():void
{
	switch (active)
	{
		case "Pencil" :
			board.removeEventListener(MouseEvent.MOUSE_DOWN, startPencilTool);
			board.removeEventListener(MouseEvent.MOUSE_UP, stopPencilTool);
		case "Eraser" :
			board.removeEventListener(MouseEvent.MOUSE_DOWN, startEraserTool);
			board.removeEventListener(MouseEvent.MOUSE_UP, stopEraserTool);
		case "Text" :
			board.removeEventListener(MouseEvent.MOUSE_UP, writeText);
		default :
	}
}

We also need to highlight the active tool and hide the other ones:

private function highlightTool(tool:DisplayObject):void
{
	tool.visible=true; //Highlights tool in the parameter
}

/* Hides the tools in the parameters */

private function hideTools(tool1:DisplayObject, tool2:DisplayObject):void
{
	tool1.visible=false;
	tool2.visible=false;
}

Step 23: Shape Size

We click the Size Panel or the ShapeSize MovieClip to change the size of the Pencil, Eraser and Text Tool. The size is changed in intervals of 5, and is reset when the size is bigger or equal to 50. Take a look at the code:

private function changeShapeSize(e:MouseEvent):void
{
	if (shapeSize.width >= 50)
	{
		shapeSize.width = 1;
		shapeSize.height = 1;

		/* TextFormat */

		textformat.size = 16;
	}
	else
	{
		shapeSize.width += 5;
		shapeSize.height=shapeSize.width;

		/* TextFormat */

		textformat.size+=5;
	}
}

Step 24: Add Listeners

A function to add all the listeners.

private function addListeners():void
{
	pencilTool.addEventListener(MouseEvent.MOUSE_UP, PencilTool);
	eraserTool.addEventListener(MouseEvent.MOUSE_UP, EraserTool);
	textTool.addEventListener(MouseEvent.MOUSE_UP, TextTool);
	saveButton.addEventListener(MouseEvent.MOUSE_UP, save);
	clearTool.addEventListener(MouseEvent.MOUSE_UP, clearBoard);
	colors.addEventListener(MouseEvent.MOUSE_UP, chooseColor);
	sizePanel.addEventListener(MouseEvent.MOUSE_UP, changeShapeSize);
	shapeSize.addEventListener(MouseEvent.MOUSE_UP, changeShapeSize);
}

Step 25: Test

Test your app by pressing cmd+return and check if everything is working as expected.

Use all the tools, colors and functions and start drawing your scene!


Conclusion

This Flash Movie can be easily adapted as a kids drawing application, it has a friendly user interface and basic tools that can teach how the mouse works whilst having some colorful fun in the process.

You can also explore the rest of the as3corelib and read its documentation to learn some new ActionScript features.

Thanks for reading!

  • Pingback: Making A Flash Drawing Tool « Media Project

  • Joe

    Great tutorial,
    How can I add a fill bucket base on the default color palette.
    please help!

  • Timothy

    Anyone know how to make this save an image to a web directory, rather than the user’s PC when they click a button?

  • aniket

    hey it was a nice tutorial…n reallly help me a lot to get through its structure.

  • harrison

    Hi! Very nice tutorial! I was wondering the following:

    1. how do you send the image file to a server
    2. how to save it to server

    I am using mysql

    Any help would be greatly appreciated! Thanks!

    • Jeremy

      Harrison, I too would love to know how to do this. Let me know if you find an answer. Please post it here.

  • elvira

    I can’t open the source .fla I have CS3. How can I open it?

  • Ray

    I was messing around with this, and I was just wondering how to make a bucket fill tool and a open image tool. Help woud be appreciated! Thanks!

  • sangram

    Guys, what is the use of such kind of artificial erasing ??? we need pixel by pixel real kind of erasing effect for a particular movieclip or an image. I think to achieve this we will need to use BitmapData Class in AS 2.0. For the AS 3.0 I have no idea. So please contact me on sangram.ssp@gmail.com if anyone of you found the solution rather than redrawing it on stage which will depend on background colour.

  • http://www.g3code.com/ Grabek

    So, in reality, you are not erasing so much as you are drawing white again, no?

  • Chris Horak

    I absolutely LOVED this tutorial. The only flaw I can find is that, when a user is drawing, and moves the mouse out of the swf, releases the button, and brings it back onto the swf, the “board” acts as if the mouse button is still being pressed, and continues to draw, following the movement of the mouse.

    How would this be fixed?

    • http://michaeljameswilliams.com/ Michael Williams

      Hey Chris,

      Have you seen Event.MOUSE_LEAVE?

  • Pingback: Advanced Character Customization for Flash Games | techglow.co.cc

  • Zee Caniago

    Hi,

    This is really what I’m looking for. Is there a way to create “open image” function? I’m new to flash, but I do have programming background.

    • http://www.acrodoodle.com Vetra

      This is an awesome little app and a great tutorial. We used the app on http://www.acrodoodle.com and people are loving it. I made just a few changes and a friend helped make the app submit to our server directly. Shows what this little guy can do. Aweomse work!

      • http://www.acrodoodle.com Vetra

        Oops. Didn’t mean for this to be a reply… anyway, great work.

  • http://none Eric Barrio

    Hi,

    I’m trying to learn as3 coming from 5+ years of as2 experience and this is a little tricky.. In the end, i have no errors in code, but a dialog box comes up in an Adobe Air file saying: An Actionscript Error Has Occured. and says that the line 220 of the code your provided about convertToBMD(); function is wrong? You are very talented. Its okay if you don’t respond but i would appreciate it!

  • Pingback: [Actionscript 3] Saving flash drawing as png in database

  • http://www.flickr.com/raphaelrpais Raphael

    Thank you so f****** much! I change many things and it’s still working great!! It was my very first Flash/AS project and I reach my objective!

  • Pingback: AS3 Tutorials | cpunx.com

  • Ram

    Awesome! Thank you for this tutorial! Is there any way to import image in the drawing board?

  • ARANDOMGIRLxD

    cant i just download something simple to do flash drawings?

  • narcy

    Thanks so much for the tut! It’s great.
    I changed it a little for my own use: what I want it’s a Board that has a picture, where a kid can overdraw. I did that. But the problem it’s the erase and when i have to clear the board…a white rectangle! Than I made a nextButton on the toolsPanel, wich could send me to a next frame where I could see the image again, instead the white board. But I’m not able to write the right code to make it work correctly, in fact the frame doesn’t stop.
    this is the code
    /* Next Tool*/
    ” private function nextButton(e:MouseEvent):void
    {

    var nextButton = goToNextFrame and stop();
    } ”
    Could someone help me?

    Thanks a lot
    Narcy

  • narcy

    Thanks so much for the tut! It’s great.
    I changed it a little for my own use: what I want it’s a Board that has a picture, where a kid can overdraw. I did that. But the problem it’s the erase and when i have to clear the board…a white rectangle! Than I made a nextButton on the toolsPanel, wich could send me to a next frame where I could see the image again, instead the white board. But I’m not able to write the right code to make it work correctly, in fact the frame doesn’t stop. Is it the right thing to do, or there is some other solution?
    this is the code I used:
    /* Next Tool*/
    ” private function nextButton(e:MouseEvent):void
    {

    var nextButton = goToNextFrame and stop();
    } ”
    Could someone help me?

    Thanks a lot
    Narcy

  • Manx Mariner

    I too would like to know if instead of saving the image if you could email the image from within the app or by launching their email app and attaching the PNG?

  • tred

    To email the image you should convert it to BASE64 format. Just google something like “AS3 BASE64 Incoder”

  • Pingback: Create a Basic Drawing Application in Flash - Flash24h.com | Thế giới Flash của bạn!

  • Pingback: Create a Basic Drawing Application in Flash « GuarniBlog

  • Azzurri

    This is unreal, i love it, and exactly what im trying to do, only thing i am struggling with is, when the images are saved to my desktop, they are saved as .file :S and not openable PNG’s …

    Can the images be saved as jpgs or even pngs, as i cant open the saved images :S

  • Tiago

    awesome tutorial man, it opens up possibilities to customize a lot, ty

  • n00b

    Thanks for a terrific tutorial!

    This was my first venture into as3 and your instructions made it much less painful.

    I made several changes, but one in particular I thought I should share…

    I wanted my background to be transparent, so that I can display the resulting .png on any color of background and not have a white block looking tacky.

    It worked a treat unless someone needed to clear the screen, then I was back to the white background.

    My resolution for that was to change the clearBoard function. I kept the function, but replaced code inside with one line:

    board.removeChild(pencilDraw);

    This seems to work well to remove the shape, without interfering with the board. :)

    Thanks again for pointing me in the right direction with your excellent tutorial!

  • n00b

    After further inspection, it appears that board.removeChild(pencilDraw); only removes the most recently drawn line.

    If anyone has any suggestions, I’d be delighted to hear them!

    • http://michaeljameswilliams.com/ Michael James Williams

      You could try looping through all the children of the board and removing them one by one. Let me know how that works out — I’ve got other ideas ;)

      • n00b

        Thanks for the idea Mr. Williams. I’ve been playing with your suggestion some and discovered that I need to learn how to identify the children. I’m working on that now, but did not want your reply to go unnoticed.

        I’ll post back what I wind up with, but I have limited free time to work on it, so it may be a little bit.

        Thanks again, your suggestion has been most helpful!

      • http://michaeljameswilliams.com/ Michael James Williams

        If you’d like a hint, click this link :)

      • n00b

        Thanks for the hint, Mr. Williams. :)

        I actually came across that function when trying to figure this out, but I’m not proficient enough yet to make use of it, so here is my less than eloquent solution:

        var i:uint=1;
        while ( i<board.numChildren){
        if(i==1){board.removeChildAt(1);}
        else{
        board.removeChildAt(i);
        i++;}
        }

        I had to stick the for 'loop,' even though it only gets used once, because I kept getting out of range errors. I'll revisit it after I have a chance to spend some quality time reading as3 docs and at livedocs.adobe.com.

        I'd be happy to read any critiques. :)

      • http://michaeljameswilliams.com/ Michael James Williams

        That’s a good solution :) The reason the loop acts so weird is that the value of board.numChildren is changing because you keep removing the board’s children.

        You could simplify your code slightly by just looping numChildren times and removing the zeroth child each time, but there’s no real need to :)

      • n00b

        Hey, thanks again for the encouragement!

        I knew that I shouldn’t have needed that for loop but every thing I had tried, including variations of your most recent suggestion, all ran with either some sort of quirk or out of range error even though they compiled with no error.

        If you removed the zeroth child, after adding multiple children, it would leave the last drawn child and render the pencil tool unusable. I suspected that’s because there’s a child initially and tried changing the addChild in the start.. functions to addChildAt…, but wound up changing it back while wrestling with the loop,

        A few times, I forgot to use board.remove…() and just used remove..() which resulted in the penciltool icons and tool panel and all sorts of stuff disappearing. Incrementing the count was dumb too. I don’t know what I was thinking there.

        After I came back and read your last comment, I knew that I was right in thinking that the for loop was superfluous, so I went back in and came up with two other options that are less convoluted. :

        I like this one best and am sticking with it, just because it’s all neatly contained in one line:
        for (var i:int = 1; i 1){
        board.removeChildAt(1);
        }

        Anyway, sorry to be so wordy, but I figured I’d share what I’d found in case it can help someone else.

        Thanks again! :)

    • Karen

      N00b, it sounds like you stumbled across a solution for the lack of an undo button! (removing only last line drawn).
      I’m playing with the source although never having opened Flash (CS4) before today, as I want to make a sample to embed in a database, where I do script comfortably.
      Where do you coordinate the size of board with the location of the mouse? I tried to simply increase the size of the doc & graphic elements, but had only amusing results. Could I please have a hint as to which code to revise?
      Many Thanks!

      • n00b

        Hi Kathy,

        Sorry that I just now saw your question. I had the same problem at first. What I found is that the problem was not in the Action Script, but in the objects on the stage.

        I had resized the stage in the project properties by clicking outside of the stage to ensure that nothing was selected, then editing the width and height properties, the board by clicking once on the board and editing the width and height, and again on the tools panel.

        I got amusing results from that as well and started looking to the as3 for answers as you have. Eventually I went back to the stage and double clicked on the board which actually opened up the object for editing, what I found there was that I needed to adjust the x and y coordinates for the primitive rectangle that is the board and I had to do the same for the tools panel.

        I’m new to flash and as3 as well, so I probably haven’t used the correct terminology, but I hope it’s enough to get you to where you need to be.

        Hope you come back and see this or that you’ve discovered the solution. :)

        BTW, Michael, thanks for the nice comment on my solution. It’s encouraging for a n00b to hear that from someone who is experienced at this!

      • n00b

        Sorry I called you Kathy, Karen.

        Kathy and Karen are my sister and mom’s names and I got a bit confuzzeld. :blush:

  • n00b

    bah! I didn’t use the < and > in my last comment and the code didn’t display correctly:

    I like this one best, just because it’s all neatly contained in one line:
    for (var i:int = 1; i < board.numChildren;board.removeChildAt(i));

    This one works too:
    while (board.numChildren > 1){
    board.removeChildAt(1);
    }

    • http://michaeljameswilliams.com/ Michael James Williams

      Oh! That’ll teach me not to assume ;) Really nice elegant solution there!

      • nobs

        Awesome tutorial!

        But I have one issue. In my own app drawing dont starts in mouse position . It starts in some strange place around 20 pixels from mouse position. The source code from tutorial works but when I change x,y position or height or width of board the same problem comes.

        P.S. I use cs 5.5

  • Pingback: 23 Useful Flash Actionscript 3.0 Tutorials

  • Al

    hi!

    this is a really great tutorial, but I have some difficulties. I followed the steps EXACTLY, i mean, really EXACTLY, but i do get error at the end when I start running it. the tools just wont work. and then i realized from the demo that the DrawingApp.fla contains some elements that arent even mentioned in the tutorial and i have no idea why they are there and what i should do about them. can anyone help me, i am pretty new at as3 too. Thanks! and great work again, by the way :D

  • http://ugleh.com Ugleh

    Hi, I loved this tutorial when I first read it when it came back and I wanted to give thanks to where to is deserved.

    I made this project based off this:

    http://herp.in/draw/index.php

    As you can see its abit different. I added some bug fixes, I added a hardness/alpha feature, and I added new colors.

    I also changed the save button to a submit button which submits it to the gallery. As for the site itself I am still working on the design and script but in the meantime i let guests use it, and ive seen abit of guests mess with it.

    • Keith

      Hi,

      I’ve just been looking at your version of the drawing app under:-

      http://herp.in/draw/index.php

      How do you code those undo & redo buttons if you mind me asking?
      For example, lets say I draw a red line and then a blue line, if I press undo it erases the last line, the blue line.

      Thanks

      keith_trodden@yahoo.com

  • http://www.benzai.nl Benny

    Thanks a lot for this tutorial! It is very clear to follow. I needed to create a drawing module for a preschool project and I only needed a small part of this tutorial. This was just what I was looking for.

    But I had to use stage.board.addEventListener… to get it to work. In my case it was _game.stage.addEventListener. (_game = DocumentClass)

    Also I needed to use _canvas.mouseX / Y instead of just mouseX / Y because my canvas is inside a movieclip, it needs the local x y.

  • http://www.benzai.nl Benny

    Just a comment about step 20 the clear tool.

    Why didn’t you use graphics.clear(); ?
    Isn’t this a better way of clearing the canvas? I’ve just tested this and it works.

  • http://fanvideos.wordpress.com/ bccmee

    Wow thanks for your generosity. I’m just learning Flash and I really appreciate the source code. Very helpful indeed! I want to learn how to make interactive Flash games and activities. The Lynda.Com tutorials are a nice beginning, but I want to go further than their Essentials course. Any recommendations?

  • bom

    Awesome tutorial!
    But I have one issue. In my own app drawing dont starts in mouse position . It starts in some strange place around 20 pixels from mouse position. The source code from tutorial works but when I change x,y position or height or width of board the same problem comes.
    P.S. I use cs 5.5

  • http://none DelMondo

    Anyone know how to change the size of the board area? I’m trying to make it bigger.

    • amir

      same here. please help!

  • http://www.webinfopedia.com Prasad

    It’s really very nice application. Thanks a lot.. Can you please tell me how to change the brush size by keyboard + and – key for increase and decreasing the brush size respectively. Anyway again thanks a lot for this tutorial..

  • Margus

    Love the tutorial! Is there any way possible that when a user presses the “Save” button, the PNG would be saved automatically to the hard drive? I would like to use this as a little snippet on a Kiosk app that im building.

  • Pingback: AS2 or AS3? « Chiaroko Goes to Uni

  • Pingback: UX | Multimedia Project Planning

  • Marika

    Thanks a lot! I’d like use a picture on the board as backgroud.(book page with exercise) How can I clear the brush lines.., but the backgroud picture not? (sorry my english) :)

  • srikanth

    thanku very much

  • EdwinCastrillon

    Muchas gracias desde Colombia, excelente tutorial, se puede decir mas duro pero no mas claro. Gracias!.

  • Tasty Mouse

    This is a very nice drawing and text tool. I want it modified: when you click ‘save’ I want the image flipped horizontally.
    I use the black color only. When the drawing is saved the background should switch tot black en the drawing to white.
    How can I do this?

  • amz

    how can i do the text tool bit using action script 2.0…?

  • piggycatz

    can you wake a download link