Too Many Buttons

[SWF (width = 500, height = 500)]

var canvas:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight, false, 0xFFFFFF);
addChild(new Bitmap(canvas));

var indexCanvas:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight, false, 0xFFFFFF);

var btnNum:int = 5000;
var info:Array = [];

var brush:BitmapData = new BitmapData(10,10,false, 0xCCCCCC);
var border:Shape = new Shape();
border.graphics.lineStyle(2, 0x000000);
border.graphics.drawRect(0,0,10,10);
brush.draw(border);

var txt:TextField = TextField(addChild(new TextField()));
with (txt) height = 20, width = 50, background = 0xFFFFFF, selectable = false
var tf:TextFormat = new TextFormat();
tf.align = TextFormatAlign.RIGHT;
txt.border= true;
txt.defaultTextFormat = tf;

var redRect:Shape = Shape(addChild(new Shape()));
with (redRect.graphics) beginFill(0xFF0000), drawRect(0,0,10,10);
											  
var pnt:Point = new Point();
var r:Rectangle = new Rectangle(0,0,10,10);
for (var i:int = 0; i < btnNum; i++){
	pnt.x = r.x = int(Math.random() * stage.stageWidth);
	pnt.y = r.y = int(Math.random() * stage.stageHeight); 
	indexCanvas.fillRect(r, i);
	canvas.copyPixels(brush, brush.rect, pnt)
	info[i] = [r.x, r.y, i];	
}

addEventListener(Event.ENTER_FRAME, onCheckBtns);
function onCheckBtns(evt:Event):void{
   var currentIndex:int = indexCanvas.getPixel(mouseX, mouseY);
   if (currentIndex != 0xFFFFFF){
	 var currentBox:Array = info[currentIndex]
	 redRect.visible = true;
	 redRect.x = currentBox[0];
	 txt.y = redRect.y = currentBox[1];
	 if (mouseX < txt.width){
		 tf.align = TextFormatAlign.LEFT;
		 txt.defaultTextFormat = tf;
		 txt.x = redRect.x + 10;
	 }else{
		 tf.align = TextFormatAlign.RIGHT;
		 txt.defaultTextFormat = tf;
		 txt.x = redRect.x - txt.width;
	 }
	 txt.text = currentBox[2];
	 txt.visible = true;
   }else{
	 redRect.visible = false; 
	 txt.visible = false;
   }
}

This is a simplified example of the technique discussed in yesterdays post. The idea is to use a BitmapData image to store index values for a large number of elements that need to be able to act as if the have MouseEvents. For a more detailed description of this technique see yesterdays post.

Have a look at the swf on wonderfl

Leave a Reply

Your email address will not be published. Required fields are marked *