ByteArray - Save image

Drawing a canvas

We start with importing several classes.


import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.utils.ByteArray;
import flash.geom.Rectangle;
import flash.net.SharedObject;
import flash.events.*;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
		

We create a variable canvas and add it to the stage


var canvas:Sprite = new Image();
canvas.x = 10;
canvas.y = 10;
stage.addChild(canvas);
		

We declare several other variables, which we will later need.


var myBitmapData:BitmapData = new BitmapData (canvas.width, canvas.height, false, 0x00FFFFFF);
var bytes:ByteArray;
var child:Shape = new Shape();
var isDrawing:Boolean = false;
		

Then we give canvas some mouse functions, since we need to draw an image.


canvas.stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
canvas.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
canvas.stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
		

We sart with a function when the mouse is pressed. We enter the point where the drawing is supposed to start.


function mouseDownHandler (event:MouseEvent)
{
	isDrawing = true;
	if( isDrawing)
	{
		child.graphics.lineStyle (2, 0xFF0000);
		child.graphics.moveTo (mouseX, mouseY);
	}
}
		

The next function contains all the script to draw an image, when the mouse pressed is moving. We set a limit to the drawing, since we want the drawing only in a certain space.


function mouseMoveHandler (event:MouseEvent)
{
	if (isDrawing)
	{
		child.graphics.lineTo (mouseX, mouseY);
	}
	if(mouseX < canvas.stage.getBounds(this).x || mouseX >295)
	{
		isDrawing = false;
	}
	if(mouseY < canvas.stage.getBounds(this).y || mouseY >145)
	{
		isDrawing = false;
	}											   
}
		

When we don't want drawing to occur we do not press the mouse. However, a number of other events are then happening. First of all the drawing (child) is saved by using addChild. We then convert the drawing to a bitmap. The bitmapdata will be stored in the byteArray object.


function mouseUpHandler (event:MouseEvent)
{
	canvas.addChild (child);
	isDrawing = false;
	var rect:Rectangle = new Rectangle(0, 0, canvas.width, canvas.height);
	myBitmapData.draw (canvas);
	bytes = myBitmapData.getPixels(rect);
	bytes.position = 0;
}
		

previous  |   next