繪制矩形
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>canvas繪制矩形</title> <script type="text/javascript" src="canvas.js"></script> <style type="text/css">//讓矩形顯示置頂 body{ margin: 0; padding: 0; } </style> </head> <body onload="draw('canvas');"> <canvas id = "canvas" width="500" height="350"></canvas> </body> </html>
//canvas.js
function draw(id){ var canvas = document.getElementById(id); var context = canvas.getContext('2d'); context.fillStyle = "#000"; context.strokeStyle = "#f60"; context.lineWidth = 5; context.fillRect(0,0,500,350); context.strokeRect(50,50,180,120); }
繪制一個矩形:
1。獲取canvas元素 getElementById()
2。取得上下文 getContext()
3。填充與繪制邊框 fill() stroke()
4。設置繪制樣式 fillStyle stokeStyle 屬性
5。指定畫筆寬度 getcontext().linewidth
6。設置顏色值 通過第4步的屬性來設置
7。繪制矩形 context.fillRect(x,y,width,height)
context.strokeRect(x,y,width,height)
繪制圓形:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>canvas繪制圓形</title> <script type="text/javascript" src="canvas.js"></script> <style type="text/css"> body{ margin: 0; padding: 0; } </style> </head> <body onload="draw('canvas');"> <canvas id = "canvas" width="500" height="500"></canvas> </body> </html>
function draw(id){ var canvas = document.getElementById(id); var context = canvas.getContext('2d'); context.fillStyle = "#f1f2f3"; context.fillRect(0,0,500,500);//背景的繪制 for(var i = 0;i<10;i++){ context.beginPath(); context.arc(25*i,25*i,10*i,0,Math.PI*2,true); context.closePath(); context.fillStyle = "rgba(255,0,0,0.25)"; context.fill(); } }
效果圖;
繪制一個圓形:
1。創建開始路徑,context.beginPath()
2.創建圖形路徑,context.arc(x,y,radius,starAngle,endAngle,anticlockwise);
var radius = degress*Math.PI/180, Math.PI=180度
anticlockwise 是否順時針
3.創建完成關閉路徑,context.clasePath()
4。設置繪制樣式然后調用繪制方法進行繪制,context.filllStyle = 'rgba(255,0,0,0.25)';context.fill();
繪制文字:
function draw(id){ var canvas = document.getElementById(id); var context = canvas.getContext('2d'); context.fillStyle = "#a0f"; context.fillRect(0,0,800,300);//背景的繪制 context.fillStyle = "#fff";//文字的顏色 context.strokeStyle = "#fff"; context.fillText("小檸檬呢",50,50); context.strokeText("小小的檸檬",50,100);
繪制動畫
var i; function draw(id){ var canvas = document.getElementById(id); context = canvas.getContext('2d'); setInterval(painting,100);//設置動畫的間隔時間。第一個參數表示執行動畫的函數,第二個函數 間隔時間 //通過不斷地變化xy坐標來實現動畫效果。clearRect(),將畫布整體或者局部擦除。 i=0; } function painting(){ context.fillStyle = "#f00"; context.fillRect(i,0,10,10); i=i+20; }