HTML5 Canvas一些常用的操作

粗略的Canvas API


1、 context

  • var context = canvas.getContext('2d');

2、Canvas state

  • context.save();//将当前状态压入状态栈中,保存当前的状态
  • context.restore();//将状态栈中的栈顶元素出栈,恢复上次的状态

3、Line styles

  • context.lineWidth[= value] ;//线宽
  • context.lineCap[= value]; //线的开始和结束部分的形状(butt:没有,round:圆,square:方)
  • context.lineJoin[= value]; // 线相交部分的形状(bevel:尖角,round:圆角,miter:按照一个既定值来设置)
  • context.miterLimit[= value]; //设置context.lineJoin为miter时的既定值。
  • context.setLineDash()
  • context.getLineDash()
  • context.lineDashOffset

4、Text styles

  • context.font [= value];//字体,和CSS写法一致
  • context.textAlign [= value];// 水平对齐(start,end,left,right,middle)
  • context.textBaseLine [=value];//设置竖直方向的基准线 (取值:top,hanging,middle,alphabetic,ideographic,bottom)

5、Building Path

  • context.moveTo(x,y);
  • context.closePath();
  • context.lineTo(x,y);
  • context.quadraticCurveTo(cpx,cpy,x,y);//2次贝塞尔曲线
  • context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);//3次贝塞尔曲线
  • context.arcTo(x1,y1,x2,y2,radius);//画一段圆弧
  • context.arc(x,y,radius,startAngle,endAngle);//画一段圆弧
  • context.rect(x,y,w,h);//画一个矩形

6、Transformations

  • context.scale(x,y);//缩放
  • context.rotate(angle);//旋转
  • context.translate(x,y);//平移
  • context.transform(a,b,c,d,e,f);
  • context.setTransform(a,b,c,d,e,f);

7、Fill and stroke styles

  • context.fillStyle [= value];//填充
  • context.strokeStyle [= value];//描边
  • 填充和描边的值可以为:CSS color,CancasGradient(canvas的渐变效果),CanvasPattern
  • var gradient = context.createLinearGradient(x0,y0,x1,y1);//线性渐变
  • var gradient = context.createRadialGradient(x0,y0,r0,x1,y1,r1);//放射性渐变
  • gradient.addColorStop(offset,color);//设置每个阶段的过渡颜色(offset为0.0~1.0之间)
  • var pattern =context.createPattern(image,repetition);//设置背景图以及重复效果,image的值可以为HTMLImageElement,HTMLCanvasElement,HTMLVideoElement。repetition的值为:repeat,repeat-x,repeat-y,no-repeat

8、Drawing rectangles to the canvas

  • context.clearRect(x,y,w,h);//清楚某个矩形区域内的所有图形
  • context.fillRect(x,y,w,h);//填充某个矩形区域
  • context.strokeRect(x,y,w,h);//对某个矩形区域进行描边

9、Drawing text to the canvas

  • context.fillText(text,x,y,[,maxWidth]);//填充文字,参数依次为:要填写的值,起始x坐标,起始y坐标,最大宽度(可选))
  • context.strokeText(text,x,y,[,maxWidth]);//对字体进行描边
  • var metrics = context.measureText(text);
  • metrics.width;

10、Drawing paths to the canvas

  • context.beginPath();
  • context.fill();
  • context.stroke();
  • context.drawFocusIfNeed(element);
  • context.clip();
  • context.isPoingInPath(x,y);

11、Dawing images to the canvas

  • context.drawImage(image,dx,dy);
  • context.drawImage(image,dx,dy,dw,dh);
  • context.drawImage(image,sx,sy,sw,sh,dx,dy,dw,dh);//其中s开头的属性表示为图像源的属性,d开头的属性表示在canvas上的属性。
  • image 的值为 HTMLImageElement,HTMLCanvasElement,HTMLVideoElement

 

参考资料:http://www.w3.org/TR/2dcontext/ 

posted @ 2014-11-18 14:12  april吖~  阅读(856)  评论(0编辑  收藏  举报