Packageflash.geom
Classpublic class Bezier
ImplementsIParametric

Class Bezier represents a Bezier second-order curve in parametric view, and is given by start, control and end points on the plane. It exists to support the curveTo() method. Methods and properties of this class give access to the geometric properties of the curve.


Brief information about the Bezier second-order curve.

Any point Pt on the Bezier second-order curve is computed using formula:

Pt = S*(1-t)2  + 2*C*(1-t)*t + E*t2     (1)


where:
t(time) — time-iterator of the point
S(start) — initial control (anchor) point (t=0)
С(control) — direction point
E(end) — final control (anchor) point (t=1)

The curve is built by iterative computing of the curve points with time-iterator modification from 0 to 1
Bezier curve point is characterized by it's time-iterator. Two curve points with the same time-iterator coincide. Generally, two curve points with different time-iterator do not coincide.

Interactive demo
You can use "Left" and "Right" keys to control the iterator.
Curve control points are dragable.



Bezier second-order curve properties

Bezier curve and parabola

Bezier second-order curve is a parabola segment. Curve built from formula 1 with iterator t changing in infinite limits is a parabola. If Bezier curve lies on parabola then this parabola is considered to be the parent for it.
This property also applies to the Bezier curves with other orders. For example, segment can be considered as Bezier first-order curve and it's parent will be the line that contains it. Class Line interprets segment this way to simplify it's usage together with Bezier class.
Bezier third-order curve on the plane is a segment of projection of cubic parabola in a three-dimensional space on the plane. General case: Bezier N-order curve is a segment of projection of the N-order curve built in N-dimensional space.

See also

Line
Intersection


Public Properties
 PropertyDefined by
  area : Number
[read-only] Calculates and returns the area of the figure limited by Bezier curve and line SE.
Bezier
  bounds : Rectangle
[read-only] Calculates and returns a bounds rectangular of a segment of Bezier curve.
Property isSegment=false does not change result of calculations.
Bezier
  control : Point
Direction point of Bezier curve.
Bezier
  end : Point
End anchor point of Bezier curve.
Bezier
  externalCentroid : Point
[read-only] Gravity center of the figure limited by Bezier curve and lines SC and CE.
Bezier
  internalCentroid : Point
[read-only] Gravity center of the figure limited by Bezier curve and line SE.
Bezier
  isSegment : Boolean
Defines is the Bezier curve is infinite in both directions or is limited within the bounds of value of iterators from 0 up to 1.

The Bezier curve is constructed with using iterator within the bounds from 0 up to 1, however, it can be constructed in any bounds.
The Bezier curve constructed from a minus of infinity up to plus of infinity is a parabola.

Current value isSegment influence on the results of methods:
intersectionBezier
intersectionLine
getClosest
Line.intersectionBezier
Bezier
  length : Number
[read-only] Calculates length of the Bezier curve
Bezier
  parabolaFocusPoint : Point
[read-only]
Bezier
  parabolaVertex : Number
[read-only] Calculates and returns time-iterator of top of the parabola.
Bezier
  start : Point
Initial anchor point of Bezier curve.
Bezier
  triangleArea : Number
[read-only] Calculates and returns the area of a triangle ∆SCE, which is formed of control points start, control, end.
Bezier
  triangleCentroid : Point
[read-only] Gravity center of triangle SCE.
Bezier
Protected Properties
 PropertyDefined by
  controlPoint : Point
Bezier
  endPoint : Point
Bezier
  __isSegment : Boolean = true
Bezier
  startPoint : Point
Bezier
Public Methods
 MethodDefined by
  
Bezier(start:Point, control:Point, end:Point, isSegment:Boolean = true)
Create new Bezier object.
Bezier
  
angleOffset(value:Number, fulcrum:Point = null):void
Rotate a curve concerning to a point fulcrum on the value angle If point fulcrum is not set, used (0,0)
Bezier
  
Creates and returns a copy of current object Bezier.
Bezier
  
getClosest(fromPoint:Point):Number

Вычисляет и возвращает time-итератор точки на кривой, ближайшей к точке fromPoint.
В зависимости от значения свойства isSegment возвращает либо значение в пределах от 0 до 1, либо от минус бесконечности до плюс бесконечности.

Bezier
  
getPoint(time:Number, point:Point = null):Point
Realization of formula 1
Calculates and returns object Point which representing a point on a Bezier curve, specified by the parameter time.
Bezier
  
getSegment(fromTime:Number = 0, toTime:Number = 1):Bezier
Вычисляет и возвращает сегмент кривой Безье.
Bezier
  
getSegmentLength(time:Number):Number
Calculates length of a segment of Bezier curve from a starting point up to a point on a curve which passed in parameter time.
Bezier
  
getTangentAngle(time:Number = 0):Number
Tangent is line that touches but does not intersect with bezier.
Bezier
  
getTimeByDistance(distance:Number):Number
Вычисляет time-итератор точки, находящейся на заданной дистанции по кривой от точки start
Для вычисления равноуделенных последовательностей точек, например для рисования пунктиром, используйте метод getTimesSequence
Bezier
  
getTimesSequence(step:Number, startShift:Number = 0):Array
Вычисляет и возвращает массив time-итераторов точек, находящихся друг от друга на дистанции по кривой, заданной параметром step.
Если задан параметр startShift, то расчет производится не от точки start, а от точки на кривой, находящейся на заданнй этим параметром дистанции.
Значение startShift конвертируется в остаток от деления на step.
Bezier
  
Результат вычисления пересечения кривой Безье с другой кривой Безье может дать следующие результаты:
- если пересечение отсутствует, возвращается null;
- если пересечение произошло в точках (от одной до четырех точек), будет возвращен объект Intersection, и time-итераторы точек пересечения на данной кривой Безье будут находиться в массиве currentTimes.
Bezier
  
Результат вычисления пересечения кривой Безье с линией может дать следующие результаты:
- если пересечение отсутствует, возвращается null;
- если пересечение произошло в одной или двух точках, будет возвращен объект Intersection, и time-итераторы точек пересечения на кривой Безье будут находиться в массиве currentTimes.
Bezier
  
offset(dX:Number = 0, dY:Number = 0):void
Moves a curve on the prescribed distance on axes X and Y.
Bezier
  
setPoint(time:Number, x:Number, y:Number):void
Изменяет кривую таким образом, что заданная параметром time точка кривой Pt, будет находиться в заданных параметрами x и y координатах.
Если один из параметров x или y не задан, то точка Pt не изменит значение соответствующей координаты.
Bezier
  
toString():String
Bezier
Protected Methods
 MethodDefined by
  
initInstance(start:Point, control:Point, end:Point, isSegment:Boolean = true):void
Bezier
Protected Constants
 ConstantDefined by
  PRECISION : Number = 1e-10
[static]
Bezier
Property detail
areaproperty
area:Number  [read-only]

Calculates and returns the area of the figure limited by Bezier curve and line SE. The area of this figure makes 2/3 areas of a triangle ∆SCE, which is formed of control points start, control, end.
Accordingly, the rest of a triangle makes 1/3 its areas.

Implementation
    public function get area():Number

See also


Example
      import flash.geom.Bezier;
   import flash.geom.Point;
      function randomPoint():Point {
   return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
   return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
      const randomBezier:Bezier = randomBezier();
      trace("bezier area: "+randomBezier.area);
      

boundsproperty 
bounds:Rectangle  [read-only]

Calculates and returns a bounds rectangular of a segment of Bezier curve.
Property isSegment=false does not change result of calculations.

Implementation
    public function get bounds():Rectangle
controlproperty 
control:Point  [read-write]

Direction point of Bezier curve.

Implementation
    public function get control():Point
    public function set control(value:Point):void
controlPointproperty 
protected var controlPoint:Point
endproperty 
end:Point  [read-write]

End anchor point of Bezier curve. Iterator time is equal to one

Implementation
    public function get end():Point
    public function set end(value:Point):void
endPointproperty 
protected var endPoint:Point
externalCentroidproperty 
externalCentroid:Point  [read-only]

Gravity center of the figure limited by Bezier curve and lines SC and CE.

Implementation
    public function get externalCentroid():Point
internalCentroidproperty 
internalCentroid:Point  [read-only]

Gravity center of the figure limited by Bezier curve and line SE.

Implementation
    public function get internalCentroid():Point
__isSegmentproperty 
protected var __isSegment:Boolean = true
isSegmentproperty 
isSegment:Boolean  [read-write]

Defines is the Bezier curve is infinite in both directions or is limited within the bounds of value of iterators from 0 up to 1.

The Bezier curve is constructed with using iterator within the bounds from 0 up to 1, however, it can be constructed in any bounds.
The Bezier curve constructed from a minus of infinity up to plus of infinity is a parabola.

Current value isSegment influence on the results of methods:
intersectionBezier
intersectionLine
getClosest
Line.intersectionBezier

The default value is true.

Implementation
    public function get isSegment():Boolean
    public function set isSegment(value:Boolean):void

See also

lengthproperty 
length:Number  [read-only]

Calculates length of the Bezier curve

Implementation
    public function get length():Number

See also


Example
In this example creates random Bezier curve and traces its length.
      import flash.geom.Bezier;
   import flash.geom.Point;
      function randomPoint():Point {
   return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
   return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
      const bezier:Bezier = randomBezier();
      trace("bezier length: "+bezier.length);
      

parabolaFocusPointproperty 
parabolaFocusPoint:Point  [read-only]

Implementation
    public function get parabolaFocusPoint():Point

See also

parabolaVertexproperty 
parabolaVertex:Number  [read-only]

Calculates and returns time-iterator of top of the parabola.

Implementation
    public function get parabolaVertex():Number

See also


Example
   import flash.geom.Bezier;
   import flash.geom.Point;
      function randomPoint():Point {
   return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
   return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
      const randomBezier:Bezier = randomBezier();
      trace("parabola vertex time: "+randomBezier.parabolaVertex);
      

startproperty 
start:Point  [read-write]

Initial anchor point of Bezier curve. Iterator time is equal to zero.

Implementation
    public function get start():Point
    public function set start(value:Point):void
startPointproperty 
protected var startPoint:Point
triangleAreaproperty 
triangleArea:Number  [read-only]

Calculates and returns the area of a triangle ∆SCE, which is formed of control points start, control, end.

Implementation
    public function get triangleArea():Number

See also

triangleCentroidproperty 
triangleCentroid:Point  [read-only]

Gravity center of triangle SCE.

Implementation
    public function get triangleCentroid():Point
Constructor detail
Bezier()constructor
public function Bezier(start:Point, control:Point, end:Point, isSegment:Boolean = true)

Create new Bezier object. If parameters are not passed, all control points are created in coordinates 0,0

Parameters
start:Point — initial point of Bezier curve
 
control:Point — control point of Bezier curve
 
end:Point — end point of Bezier curve
 
isSegment:Boolean (default = true) — operating mode

Example
In this example created Bezier curve with random coordinates.
   import flash.geom.Bezier;
   import flash.geom.Point;
      function randomPoint():Point {
   return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
   return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
      const bezier:Bezier = randomBezier();
   trace("random bezier: "+bezier);
   

Method detail
angleOffset()method
public function angleOffset(value:Number, fulcrum:Point = null):void

Rotate a curve concerning to a point fulcrum on the value angle If point fulcrum is not set, used (0,0)

Parameters
value:Number — rotation angle
 
fulcrum:Point (default = null) — center of rotation.
clone()method 
public function clone():Bezier

Creates and returns a copy of current object Bezier.

Returns
Bezier — Bezier.

Example
In this example creates random Bezier curve and its copy.
   import flash.geom.Bezier;
   import flash.geom.Point;
      function randomPoint():Point {
   return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
   return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
      const bezier:Bezier = randomBezier();
   const clone:Bezier = bezier.clone();
   trace("bezier: "+bezier);
   trace("clone: "+clone);
   trace(bezier == clone);
      

getClosest()method 
public function getClosest(fromPoint:Point):Number

Вычисляет и возвращает time-итератор точки на кривой, ближайшей к точке fromPoint.
В зависимости от значения свойства isSegment возвращает либо значение в пределах от 0 до 1, либо от минус бесконечности до плюс бесконечности.

Parameters
fromPoint:Point — произвольная точка на плоскости.

Returns
Number — Number time-итератор точки на кривой.

See also


Example
   import flash.geom.Bezier;
    import flash.geom.Point;
   
   function randomPoint():Point {
    return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
    return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
   
   const bezier:Bezier = randomBezier();
   
   TODO: [Dembicki] example
   
   

getPoint()method 
public function getPoint(time:Number, point:Point = null):Point

Realization of formula 1
Calculates and returns object Point which representing a point on a Bezier curve, specified by the parameter time.

Parameters
time:Number — iterator of the point on curve
 
point:Point (default = null)

Returns
Point — Point point on the Bezier curve;
If passed the parameter time equal to 1 or 0, object Point equivalent to start or end will be returned, but not objects exact start or end.

Example
      import flash.geom.Bezier;
   import flash.geom.Point;
      function randomPoint():Point {
   return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
   return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
      const bezier:Bezier = randomBezier();
      const time:Number = Math.random();
   const point:Point = bezier.getPoint(time);
      trace(point);
   

getSegment()method 
public function getSegment(fromTime:Number = 0, toTime:Number = 1):Bezier

Вычисляет и возвращает сегмент кривой Безье.

Parameters
fromTime:Number (default = 0) — time-итератор начальной точки сегмента
 
toTime:Number (default = 1) — time-итератор конечной точки сегмента кривой

Returns
Bezier — Bezier;

Example
В данном примере на основе случайной кривой Безье создаются еще две. Первая из них - segment1
   import flash.geom.Bezier;
    import flash.geom.Point;
   
   function randomPoint():Point {
    return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
    return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
   
   const bezier:Bezier = randomBezier();
   const segment1:Bezier = bezier.getSegment(1/3, 2/3);
   const segment2:Bezier = bezier.getSegment(-1, 2);
   
   

getSegmentLength()method 
public function getSegmentLength(time:Number):Number

Calculates length of a segment of Bezier curve from a starting point up to a point on a curve which passed in parameter time.

Parameters
time:Number — parameter time of the end point of a segment.

Returns
Number — Number length of arc.

See also


Example
In this example creates random Bezier curve, calculates time-iterator of the middle of a curve, and then traces values of half of length of a curve and length of a segment of a curve up to an middle point - they should be equal.

getTangentAngle()method 
public function getTangentAngle(time:Number = 0):Number

Tangent is line that touches but does not intersect with bezier. Computes and returns the angle of tangent line in radians. The return value is between positive pi and negative pi.

Parameters
time:Number (default = 0) — time of bezier point

Returns
Number — Number angle in radians;

Example
   import flash.geom.Bezier;
    import flash.geom.Point;
   
   function randomPoint():Point {
    return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
    return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
   
   const bezier:Bezier = randomBezier();
   

getTimeByDistance()method 
public function getTimeByDistance(distance:Number):Number

Вычисляет time-итератор точки, находящейся на заданной дистанции по кривой от точки start
Для вычисления равноуделенных последовательностей точек, например для рисования пунктиром, используйте метод getTimesSequence

Parameters
distance:Number — дистанция по кривой до искомой точки.

Returns
Number — Number time iterator of bezier point;

See also


Example
   
   import flash.geom.Bezier;
   import flash.geom.Point;
   
   function randomPoint():Point {
    return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
    return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
   
   const bezier:Bezier = randomBezier();
   
   trace(bezier.getTimeByDistance(-10); // negative value
   trace(bezier.getTimeByDistance(bezier.length/2); // value between 0 and 1
   

getTimesSequence()method 
public function getTimesSequence(step:Number, startShift:Number = 0):Array

Вычисляет и возвращает массив time-итераторов точек, находящихся друг от друга на дистанции по кривой, заданной параметром step.
Если задан параметр startShift, то расчет производится не от точки start, а от точки на кривой, находящейся на заданнй этим параметром дистанции.
Значение startShift конвертируется в остаток от деления на step.

Parameters
step:Number — шаг, дистанция по кривой между точками.
 
startShift:Number (default = 0) — дистанция по кривой, задающая смещение первой точки последовательности относительно точки start

Returns
Array — Array sequence of points on bezier curve;

Example
   
   import flash.geom.Bezier;
   import flash.geom.Point;
   
   function randomPoint():Point {
    return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
    return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
   
   const bezier:Bezier = randomBezier();
   
   // TODO: [Dembicki] example 
   
   

initInstance()method 
protected function initInstance(start:Point, control:Point, end:Point, isSegment:Boolean = true):voidParameters
start:Point
 
control:Point
 
end:Point
 
isSegment:Boolean (default = true)
intersectionBezier()method 
public function intersectionBezier(target:Bezier):Intersection

Результат вычисления пересечения кривой Безье с другой кривой Безье может дать следующие результаты:
- если пересечение отсутствует, возвращается null;
- если пересечение произошло в точках (от одной до четырех точек), будет возвращен объект Intersection, и time-итераторы точек пересечения на данной кривой Безье будут находиться в массиве currentTimes. time-итераторы точек пересечения target будут находиться в массиве targetTimes;
- также может произойти совпадение кривых. В этом случае результатом будет являться кривая - объект Bezier (isSegment=true), которая будет доступна как свойство coincidenceBezier в возвращаемом объекте Intersection;

На результаты вычисления пересечений оказывает влияние свойство isSegment как текущего объекта, так и значение isSegment объекта target.

Parameters
target:Bezier

Returns
Intersection — Intersection

Example
   import flash.geom.Bezier;
    import flash.geom.Point;
   
   function randomPoint():Point {
    return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
    return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
   
   const bezier:Bezier = randomBezier();
   

intersectionLine()method 
public function intersectionLine(target:Line):Intersection

Результат вычисления пересечения кривой Безье с линией может дать следующие результаты:
- если пересечение отсутствует, возвращается null;
- если пересечение произошло в одной или двух точках, будет возвращен объект Intersection, и time-итераторы точек пересечения на кривой Безье будут находиться в массиве currentTimes. time-итераторы точек пересечения target будут находиться в массиве targetTimes;
- если кривая Безье вырождена, то может произойти совпадение. В этом случае результатом будет являться отрезок - объект Line (isSegment=true), который будет доступен как свойство coincidenceLine в возвращаемом объекте Intersection;

На результаты вычисления пересечений оказывает влияние свойство isSegment как текущего объекта, так и значение isSegment объекта target.

Parameters
target:Line

Returns
Intersection — Intersection

See also


Example
   import flash.geom.Bezier;
    import flash.geom.Point;
   
   function randomPoint():Point {
    return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
    return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
   
   const bezier:Bezier = randomBezier();
   

offset()method 
public function offset(dX:Number = 0, dY:Number = 0):void

Moves a curve on the prescribed distance on axes X and Y.

Parameters
dX:Number (default = 0) — offset by X
 
dY:Number (default = 0) — offset by Y
setPoint()method 
public function setPoint(time:Number, x:Number, y:Number):void

Изменяет кривую таким образом, что заданная параметром time точка кривой Pt, будет находиться в заданных параметрами x и y координатах.
Если один из параметров x или y не задан, то точка Pt не изменит значение соответствующей координаты.

Parameters
time:Number — time-итератор точки кривой.
 
x:Number — новое значение позиции точки по оси X.
 
y:Number — новое значение позиции точки по оси Y.

Example
   
   import flash.geom.Bezier;
    import flash.geom.Point;
   
   function randomPoint():Point {
    return new Point(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
   }
   function randomBezier():Bezier {
    return new Bezier(randomPoint(), randomPoint(), randomPoint());
   }
   
   const bezier:Bezier = randomBezier();
   trace(bezier);
   
   bezier.setPoint(0, 0, 0);
   bezier.setPoint(0.5, 100, 100);
   bezier.setPoint(1, 200, 0);
   
   trace(bezier); // (start:(x=0, y=0), control:(x=100, y=200), end:(x=200, y=0))
   

toString()method 
public function toString():String

Returns
String — String
Constant detail
PRECISIONconstant
protected static const PRECISION:Number = 1e-10