canvas能用于繪制各種圖形,那么如何使用HTML5 canvas繪制一個(gè)圓形呢?本篇文章就來給大家介紹關(guān)于HTML5 canvas繪制圓形的方法,下面我們來看具體的內(nèi)容。
我們來直接看示例
代碼如下
<!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>
運(yùn)行結(jié)果
瀏覽器上執(zhí)行上述HTML文件。將會(huì)顯示如下效果
最后說明一點(diǎn)
arc()方法給出的圓的坐標(biāo)是圓的中心坐標(biāo)。
在上述的HTML代碼中,將繪圖部分設(shè)為下面的代碼。
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(); }
上述代碼的顯示效果如下,可以看到中心坐標(biāo)是圓的中心。