目录

Drawing Paths

我们需要以下方法在画布上绘制路径 -

S.No. 方法和描述
1

beginPath()

此方法重置当前路径。

2

moveTo(x, y)

此方法使用给定点创建新的子路径。

3

closePath()

此方法将当前子路径标记为已关闭,并启动一个新的子路径,其点与新关闭的子路径的开始和结束相同。

4

fill()

此方法使用当前填充样式填充子路径。

5

stroke()

此方法使用当前笔触样式描绘子路径。

6

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

将点添加到子路径,使得由参数描述的圆周描述的弧,从给定的起始角开始,以给定的结束角度结束,沿给定的方向,被添加到路径,连接到前一点由一条直线。

例子 (Example)

以下是利用上述方法绘制形状的简单示例。

<!DOCTYPE HTML>
<html>
   <head>
      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      <script type = "text/javascript">
         function drawShape() {
            // get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');
            // 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.');
            }
         }
      </script>
   </head>
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
</html>

它将产生以下输出 -

新页面打开
↑回到顶部↑
WIKI教程 @2018