Reputation: 15
Ok, the idea is simple, set of buttons on the stage, click the button change to color to draw with. I'm trying to learn flash & actionscript and not really sure where my problem is, but I can not figure out how to do this.
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Artist extends Sprite {
public var drawing:Boolean;
public var colorArray:Array;
public var dc;
public function colors() {
colorArray = ["0xFF0000","0xFFA500","0xFFFF00","0x00FF00","0x0000FF","0x4B0082","0x8F00FF","0xFF69B4","0x00CCFF","0x008000","0x8B4513"];
for (var i:int = 0; i < colorArray.length; i++) {
this["btn_" + i].addEventListener(MouseEvent.CLICK, set_color);
}
}
public function set_color(e:MouseEvent):void {
dc = colorArray;
}
public function Artist() {
graphics.lineStyle(10,dc);
drawing = false;
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_MOVE, draw);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
}
public function startDrawing(event:MouseEvent):void {
graphics.moveTo( mouseX, mouseY);
drawing = true;
}
public function draw(event:MouseEvent) {
if(drawing) {
graphics.lineTo(mouseX,mouseY);
}
}
public function stopDrawing(event:MouseEvent) {
drawing = false;
}
}
}
Upvotes: 0
Views: 1546
Reputation: 4221
You should get the index by the button name, then you can assign the color using the clicked index.
for (var i:int = 0; i < colorArray.length; i++) {
this["btn_" + i].addEventListener(MouseEvent.CLICK, set_color);
}
public function set_color(e:MouseEvent):void {
// Get the button name and fetch it's index
var index:int = int(e.currentTarget.name.substring(4));
dc = colorArray[index];
}
Also, make sure the colorArray is known throughout the whole class if you want to access it in methods.
Just define it outside the colors
method as Lukasz said:
protected var colorArray:Array
and use numbers not strings for colors 0xFF0000
instead of "0xFF0000"
Upvotes: 1
Reputation: 9897
Use tag
property on Button to put color (or color index) to button itself, then in click handler read this tag via event.sender.tag
.
You can also generate your buttons with tags from color array (and names from another array.)
Upvotes: 0