繪製矩形
<!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); }
<!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(); } }
效果圖;javascript
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);
繪製動畫css
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; }