使用﹤canvas.../﹥元素绘图的关键步骤是:①获取 CanvasRenderingContext2D对象:②调用 CanvasRenderingContext2D对象的方法进行绘图。
每个﹤canvas.../﹥元素对应于一个 Canvas 对象,Canvas 对象的getContext(String contextID)方法将会返回一个绘图 API,该方法需要一个字符串参数,目前该方法只支持"2d"字符串作为参数,该方法将会返回一个 CanvasRenderingContext2D对象。
CanvasRenderingContext2D提供的方法
void arc(float ×, float y, float radius, float startAngle, endAngle, boolean,counterclockwise)——向Canvas的当前路径上添加一段弧
void arcTo(float x1, float y1, float x2, float y2, float radius)——向Canvas的当前路径上添加一段。与前一个方法相比,只是定义弧的方式不同
void beginPath( )——开始定义路径
void closePath( )——关闭当前定义的路径
void bezierCurve To(float cpX1, float cpY1, float cpX2, float cp Y2, float x, float y)——向Canvas的当前路径上添加一段贝济埃曲线
void clearRect(float x, float y, float width, float height)——擦除指定矩形区域上绘制的图形
void clip( )——从画布上裁剪一块出来
CanvasGradient createLinearGradient(float ×Start, float Start, float ×End, float yEnd)——创建一个线性渐变
CanvasPattern createPattern (Image image,String style)——创建一个图形平铺
CanvasGradient createRadialGradient(float ×Start, float yStart, float radiusStart, float ×End, float yEnd, float radiusEnd)——创建一个圆形渐变
{void drawImage(Image image, float x, float y)、void drawImage(Image image, float x, float y, float width, float height)、void drawImage(Image image, integer sx, integer sy, integer sw, integer sh, float dx,float dy, float dw, float dh)}——绘制位图
void fill( )——填充Canvas的当前路径
void fillRect(float x, float y, float width, float height)——填充一个矩形区域
void fillText(String text, float ×, float y , [float max Width])——填充字符串
void lineTo(float x, float y)——把Canvas的当前路径从当前结束点连接到x、y对应的点
void moveTo(float ×, float y)——把Canvas的当前路径的结束点移动到x、y对应的点
void quadraticCurve To(float cpX, float cp Y, float ×, float y)——向Canvas的当前路径上添加一段二次曲线
void rect(float x, float y, float width, float height)——向Canvas的当前路径上添加一个矩形
void stroke( )——沿着Canvas的当前路径绘制边框
void strokeRect(float x, float y, float width, float height)——绘制一个矩形边框
void stroke Text(String text, float x, float y , [float max Width])——绘制字符串的边框
void save( )——保存当前绘图状态
void restore( )——恢复之前保存的绘图状态
void rotate(float angle)——旋转坐标系统
void scale(float sx, float sy)——缩放坐标系统
void translate(float dx, float dy)——平移坐标系统
CanvasRenderingContext2D提供的属性
fillStyle:设置填充路径时所用的填充风格。该属性支持了种类型的值:
1.符合颜色格式的字符串值,表明使用纯色填充
2.CanvasGradient, 表明使用渐变填充
3.CanvasPattern,表明使用位图填充
strokeStyle:设置绘制路径时所用的填充风格。该属性支持3种类型的值:
1.符合颜色格式的字符串值,表明使用纯色填充
2.CanvasGradient, 表明使用渐变填充
3.CanvasPattern,表明使用位图填充
font:设置绘制字符串时所用的字体
globalAlpha:设置全局透明度
globalCompositeOperation:设置全局的叠加效果
lineCap:设置线段端点的绘制形状。该属性支持如下 3个值:
1.“butt”,该属性值指定不绘制端点。线条结尾处直接结束。这是默认的属性值
2.“round”,该属性值指定绘制圆形端点。线条结尾处绘制一个直径为线条宽度的半圆
3.“square”,该属性值指定绘制方形端点。线条结尾处绘制半个边长为线条完度的正方形。需要说明的是,这种形状的端点与'“butt'”形状的端点十分相似。只是采用这种形式的端点的线条略长一点而己
miterLimit:当把 lineJoin 属性设为meter 风格时,该属性控制锐角箭头的长度
line Width:设置笔触线条的宽度
shadowBlur:设置阴影的模糊度
shadowColor:设置阴影的颜色
shadowOffsetX:设置阴影在 X方向的偏移
shadowOffsetY:设置阴影在丫方向的偏移
textAlign:设置绘制字符串的水平对齐方式,该属性支持 start、end、 left、right、center 等属性值
textBaseAlign:设置绘制宇符串的垂直对齐方式,该属性支持 top、hanging、middle、alphabetic、idecgraphic、bottom 等属性值