虐了一下午的canvashtml
先擼了一個七巧板canvas
<!doctype html> <html> <head> <meta charset="utf-8"> <title>無標題文檔</title> </head> <body> <canvas id="canvas" style="border:1px solid #ccc; display:block; margin:50px auto;"> </canvas> <script> var tangram=[ {p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:'#caff67'}, {p:[{x:0,y:0},{x:400,y:400},{x:0,y:800},{x:0,y:0}],color:'#67becf'}, {p:[{x:800,y:0},{x:800,y:400},{x:600,y:600},{x:600,y:200}],color:'#ef3d61'}, {p:[{x:600,y:200},{x:600,y:600},{x:400,y:400}],color:'#f9f51a'}, {p:[{x:400,y:400},{x:600,y:600},{x:400,y:800},{x:200,y:600}],color:'#a594c0'}, {p:[{x:200,y:600},{x:400,y:800},{x:0,y:800}],color:'#fa8ecc'}, {p:[{x:800,y:400},{x:800,y:800},{x:400,y:800}],color:'#f6ca29'}, ] window.onload=function() { var canavs=document.getElementById('canvas'); canvas.width=800; canvas.height=800; var context=canvas.getContext('2d'); for(var i=0;i<tangram.length;i++) draw(tangram[i],context) } function draw(piece,cxt){ cxt.beginPath(); cxt.moveTo(piece.p[0].x,piece.p[0].y); for(var i=1;i<piece.p.length;i++) cxt.lineTo(piece.p[i].x,piece.p[i].y); cxt.closePath(); cxt.fillStyle=piece.color; cxt.fill(); } </script> </body> </html>
知道了canvas繪圖實際上是在canvas.getContext('2d')環境裏進行的,要先聲明之。spa
繪圖分兩個步驟,首先描繪路徑軌跡,而後渲染填充。3d
在頁面中存在繪製多個圖形的狀況下,避免各個路徑之間互相干擾,要把每段完整的路徑用beginPath()和closePath()包圍起來保證代碼的完整性。code
值得一提的是在路徑末端加了closePath()後,繪製的路徑會自動收尾封閉,即若是繪製了三角形的兩條邊,那麼closePath()會自動補全第三條邊使圖造成爲封閉的三角形。htm
其中繪製圓形路徑用arc(x,y,r,0,2*Math.PI,true),其中xy爲圓心座標,r爲半徑,0爲起點,2*Math.PI爲終點,true爲逆時針方向繪製該圓blog
圓形解剖:ip
將路徑變成線條使用stroke(),用lineWidth屬性設置線條的粗細,用strokeStyle設置顏色;utf-8
填充路徑用fill(),用fillStyle設置填充色。文檔
吃飯,未完待續。。。