博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

HTML5:canvas之绘制图形

Posted on 2011-12-08 19:51  zhangweia  阅读(418)  评论(0编辑  收藏  举报

https://developer.mozilla.org/cn/Canvas_tutorial/Drawing_shapes

1  绘制矩形

fillRect(x,y,width,height) : Draws a filled rectangle
strokeRect(x,y,width,height) : Draws a rectangular outline
clearRect(x,y,width,height) : Clears the specified area and makes it fully transparent
 
例子:
function draw(){
  var canvas = document.getElementById('tutorial');
  if (canvas.getContext){
    var ctx = canvas.getContext('2d');//得到画笔
    ctx.fillRect(25,25,100,100);
    ctx.clearRect(45,45,60,60);
    ctx.strokeRect(50,50,50,50);
  }
}

  效果图

    image

2. 绘制路径 draw path

beginPath()
closePath()
stroke()
fill()
moveTo(int x,int y)
 

  beginPath() : 创建一个路径

      closePath()  : 关闭一个路径

      stroke() : 空心填充路径 

      fill()        : 实心填充路径。调用fill时会自动关闭路径,不需要在调用chosePath()

     moveTo(int x,int y): 设置路径的起始点坐标

 

3. 绘制直线

lineTo(x, y)

 例子:

function drawShape(){
  // get the canvas element using the DOM
  var canvas = document.getElementById('tutorial');

  // Make sure we don't execute when canvas isn't supported
  if (canvas.getContext){

    // use getContext to use the canvas for drawing
    var ctx = canvas.getContext('2d');

    // Filled triangle
    ctx.beginPath();
    ctx.moveTo(25,25);
    ctx.lineTo(105,25);
    ctx.lineTo(25,105);
    ctx.fill();
    
    // Stroked triangle
    ctx.beginPath();
    ctx.moveTo(125,125);
    ctx.lineTo(125,45);
    ctx.lineTo(45,125);
    ctx.closePath();
    ctx.stroke();

  } else {
    alert('You need Safari or Firefox 1.5+ to see this demo.');
  }
}

 效果图:

  image

 

4. 绘制弧线

arc(x, y, radius, startAngle, endAngle, anticlockwise)

  x,y : 圆心坐标

      radius  : 半径

     startAngleendAngle 分别是起末弧度(以 x 轴为基准)

     anticlockwise 为 true 表示逆时针,反之顺时针

     例子:

function drawShape(){
  // get the canvas element using the DOM
  var canvas = document.getElementById('tutorial');

  // Make sure we don't execute when canvas isn't supported
  if (canvas.getContext){

    // use getContext to use the canvas for drawing
    var ctx = canvas.getContext('2d');

    // Draw shapes
    ctx.beginPath();
    ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle
    ctx.moveTo(110,75);
    ctx.arc(75,75,35,0,Math.PI,false);   // Mouth
    ctx.moveTo(65,65);
    ctx.arc(60,65,5,0,Math.PI*2,true);  // Left eye
    ctx.moveTo(95,65);
    ctx.arc(90,65,5,0,Math.PI*2,true);  // Right eye
    ctx.stroke();

  } else {
    alert('You need Safari or Firefox 1.5+ to see this demo.');
  }
}

  效果图:

  image

 

5.贝塞尔和二次方曲线 Bezier and quadratic curves
quadraticCurveTo(cp1x, cp1y, x, y) // BROKEN in Firefox 1.5 (see work around below)
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)