01 <canvas id="myCanvas" width="300" height="200" style="border:1px solid #c3c3c3;">
02 Your browser does not support the canvas element.
03 </canvas>
04 <script type="text/javascript">
05 var myCanvas = document.getElementById("myCanvas");
06 if (!myCanvas.getContext)
07 {
08 alert("Your browser does not support the canvas element.");
09 }
10 else
11 {
12 var myContext = myCanvas.getContext("2d");
13 myContext.fillStyle = '#0000ff';
14 myContext.strokeStyle = '#ff0000';
15 myContext.lineWidth = 2;
16 myContext.beginPath();
17 myContext.moveTo(30, 30);
18 myContext.lineTo(150, 30);
19 myContext.lineTo(150, 120);
20 myContext.lineTo(90, 100);
21 myContext.lineTo(120, 60);
22 myContext.lineTo(30, 30);
23 myContext.fill();
24 myContext.stroke();
25 myContext.closePath();
26 }
解析:
在获得渲染上下文后,设置了填充色、边框色和边框宽度。
调用beginPath()方法开始绘制路径
通过lineTo()方法绘制一个闭合的自定义图形
调用fill()方法进行填充
调用stroke()方法设置边框
调用closePath()方法结束路径的绘制