canvas能用于绘制各种图形,那么如何使用html5 canvas绘制一个圆形呢?本篇文章就来给大家介绍关于html5 canvas绘制圆形的方法,下面我们来看具体的内容。
我们来直接看示例
代码如下
<!doctype html><html><head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title></title> <meta charset="utf-8" /> <script type="text/javascript"> function draw() { var canvas = document.getelementbyid('simplecanvas'); if ( ! canvas || ! canvas.getcontext ) { return false; } var cx = 360; var cy = 400; var radius = 36; var context = canvas.getcontext('2d'); context.beginpath(); context.arc(cx, cy, radius, 0, 2 * math.pi, false); context.fillstyle = '#9fd9ef'; context.fill(); context.linewidth = 1; context.strokestyle = '#00477d'; context.stroke(); } </script></head><body onload="draw()" style="background-color:#d0d0d0;"> <canvas id="simplecanvas" width="640" height="480" style="background-color:#ffffff;"></canvas> <div>canvas demo</div></body></html>
运行结果
浏览器上执行上述html文件。将会显示如下效果
最后说明一点
arc()方法给出的圆的坐标是圆的中心坐标。
在上述的html代码中,将绘图部分设为下面的代码。
function draw() { var canvas = document.getelementbyid('simplecanvas'); if ( ! canvas || ! canvas.getcontext ) { return false; } var cx = 360; var cy = 400; var radius = 36; var context = canvas.getcontext('2d'); context.beginpath(); context.arc(cx, cy, radius, 0, 2 * math.pi, false); context.fillstyle = '#9fd9ef'; context.fill(); context.linewidth = 1; context.strokestyle = '#00477d'; context.stroke(); context.beginpath(); context.moveto(0, 0); context.lineto(cx, cy); context.stroke(); }
上述代码的显示效果如下,可以看到中心坐标是圆的中心。
以上就是html5 canvas如何绘制圆形?(代码实例)的详细内容。
