Painter 3
/**
* Copyright Saqoosha ( http://wonderfl.net/user/Saqoosha )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/de0N
*/
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.events.MouseEvent;
import flash.geom.Point;
/**
* @author Saqoosha
*/
[SWF(backgroundColor="#000000", frameRate="60", width="475", height="475")]
public class Painter3 extends Sprite
{
private var _canvasData:BitmapData = new BitmapData(475, 475, false, 0xffffff);
private var _canvas:Bitmap = new Bitmap(_canvasData);
private var _stroke:Shape = new Shape();
private var _points:Vector.<Point> = new Vector.<Point>();
public function Painter3()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(MouseEvent.MOUSE_DOWN, _mouseDownHandler);
addChild(_canvas);
addChild(_stroke);
}
private function _mouseDownHandler(event:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_MOVE, _mouseMoveHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, _mouseUpHandler);
_points.length = 0;
_stroke.graphics.lineStyle(5, 0xff0000, 0.5);
_stroke.graphics.moveTo(event.stageX, event.stageY);
}
private function _mouseMoveHandler(event:MouseEvent):void
{
_points.push(new Point(event.stageX, event.stageY));
switch (_points.length)
{
case 3:
{
new CatmullRom(_points[0], _points[0], _points[1], _points[2]).draw(_stroke.graphics);
break;
}
case 4:
{
new CatmullRom(_points[0], _points[1], _points[2], _points[3]).draw(_stroke.graphics);
_points.shift();
break;
}
}
}
private function _mouseUpHandler(event:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, _mouseMoveHandler);
stage.removeEventListener(MouseEvent.MOUSE_UP, _mouseUpHandler);
_canvasData.draw(_stroke);
_stroke.graphics.clear();
}
}
}
import flash.display.Graphics;
import flash.geom.Point;
class CatmullRom
{
public var p0:Point;
public var p1:Point;
public var p2:Point;
public var p3:Point;
public function CatmullRom(p0:Point = null, p1:Point = null, p2:Point = null, p3:Point = null)
{
this.p0 = p0 || new Point();
this.p1 = p1 || new Point();
this.p2 = p2 || new Point();
this.p3 = p3 || new Point();
}
public function getPointAt(t:Number, out:Point = null):Point
{
out ||= new Point();
var t2:Number = t * t;
var t3:Number = t2 * t;
var a:Number = -t3 + 2 * t2 - t;
var b:Number = 3 * t3 - 5 * t2 + 2;
var c:Number = -3 * t3 + 4 * t2 + t;
var d:Number = t3 - t2;
out.x = (p0.x * a + p1.x * b + p2.x * c + p3.x * d) * 0.5;
out.y = (p0.y * a + p1.y * b + p2.y * c + p3.y * d) * 0.5;
return out;
}
public function draw(graphics:Graphics, numSegments:int = 50):void
{
var p:Point = new Point();
for (var i:int = 1; i <= numSegments; ++i)
{
getPointAt(i / numSegments, p);
graphics.lineTo(p.x, p.y);
}
}
}