HTML5游戏引擎(八)-矢量绘图——绘制矩形-drawRect & 绘制圆形-drawCircle & 绘制直线-moveTo和 lineTo
矢量绘图
Egret中封装了 Graphics
类实现矢量绘图功能,可以绘制矩形、圆形、直线、曲线、圆弧等。下面介绍了矢量绘图功能的基本用法和若干高级用法。
绘制矩形
Graphics
类中封装的绘图方法不能直接使用,而需要在显示对象中使用。一些显示对象(如 Shape
和 Sprite
)中已经包含了绘图方法,因此可以在显示对象中直接调用这些方法进行绘图。
下面代码以 Shape
对象为例,绘制矩形的:
class GraphicsTest extends egret.DisplayObjectContainer
{
public constructor()
{
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
}
private onAddToStage(event:egret.Event)
{
//绘制矩形
var shp:egret.Shape = new egret.Shape();
shp.graphics.beginFill( 0xff0000, 1);
shp.graphics.drawRect( 0, 0, 100, 200 );
shp.graphics.endFill();
this.addChild( shp );
}
}
调用 beginFill()
方法设置矩形的填充颜色,这里将填充颜色设置为红色(颜色值0xff0000),同时将alpha
设置为1,表示完全不透明。
调用 drawRect()
方法设置矩形的位置和大小,前两个参数分别为矩形左上角的X、Y轴坐标(相对于 shp
的锚点计算),后两个参数分别为矩形的宽和高,这里在 (0, 0) 点绘制了一个 100*200 的矩形。
调用 endFill()
方法结束当前绘制操作。
绘制圆形
绘制圆形的方法与绘制矩形类似,只需将 drawRect()
方法改为 drawCircle()
方法。
drawCircle( x:number, y:number, radius:number): void
drawCircle()
方法接受三个参数,第一个参数为圆心的X轴坐标,第二个参数为圆心的Y轴坐标,第三个参数为半径。
注意:圆心的X轴和Y轴位置是相对于
Shape
对象的锚点计算的.
下面代码示例绘制了一个半径为50像素的圆形:
class GraphicsTest extends egret.DisplayObjectContainer
{
public constructor()
{
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
}
private onAddToStage(event:egret.Event)
{
//绘制圆形
var shp:egret.Shape = new egret.Shape();
shp.x = 100;
shp.y = 100;
shp.graphics.lineStyle( 10, 0x00ff00 );
shp.graphics.beginFill( 0xff0000, 1);
shp.graphics.drawCircle( 0, 0, 50 );
shp.graphics.endFill();
this.addChild( shp );
}
}
绘制直线
使用Graphics绘制直线需要使用两个方法: moveTo()
和 lineTo()
,它们输入参数是一对坐标值。moveTo()
负责绘制直线的起始点,lineTo()
负责绘制直线的终点。
moveTo( x:number, y:number): void
lineTo( x:number, y:number): void
在绘图直线前,需要先制定线条的样式,设置 lineStyle()
方法:
shp.graphics.lineStyle( 2, 0x00ff00 );
然后使用 moveTo()
来设定线条的起始点,使用 lineTo()
来设定线条的终点。完整代码如下:
class GraphicsTest extends egret.DisplayObjectContainer
{
public constructor()
{
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
}
private onAddToStage(event:egret.Event)
{
//绘制直线
var shp:egret.Shape = new egret.Shape();
shp.graphics.lineStyle( 2, 0x00ff00 );
shp.graphics.moveTo( 10,10 );
shp.graphics.lineTo( 100, 20 );
shp.graphics.endFill();
this.addChild( shp );
}
}
也可以连续绘制多条首尾相接的直线,形成一条折线,代码如下:
var shp:egret.Shape = new egret.Shape();
shp.graphics.lineStyle( 2, 0x00ff00 );
shp.graphics.moveTo( 68, 84 );
shp.graphics.lineTo( 167, 76 );
shp.graphics.lineTo( 221, 118 );
shp.graphics.lineTo( 290, 162 );
shp.graphics.lineTo( 297, 228 );
shp.graphics.lineTo( 412, 250 );
shp.graphics.lineTo( 443, 174 );
shp.graphics.endFill();
this.addChild( shp );
绘制折线时,无需多次使用
moveTo()
方法,连续使用lineTo()
方法即可。