<!DOCTYPE html /> <html> <head> <title>Learning the basics of canvas</title> <meta charset="utf-8" /> <script type="text/javascript" src="jquery-1.6.4.js"></script> <script type="text/javascript"> $().ready(function () { //獲取canvas對象 var canvas = $("#myCanvas"); //得到2D渲染上下文,以便開始繪製圖形 var context = canvas.get(0).getContext("2d"); //繪製矩形 context.fillRect(40, 40, 100, 100); //繪製矩形邊框 context.strokeRect(200, 200, 100, 100); //繪製線條(實際稱為路徑) //開始路徑 context.beginPath(); //設置路徑原點 context.moveTo(150, 150); //設置路徑終點 context.lineTo(300, 300); //結束路徑 context.closePath(); //繪製路徑 context.stroke(); //繪製圓形(canvas并無繪製圓形的方法,只有繪製弧形的方法) //開始路徑 context.beginPath(); //繪製一個圓形 context.arc(230, 90, 50, 0, Math.PI * 2, false); context.arc(350, 90, 50, 0, Math.PI, false); //結束路徑 context.closePath(); //context.stroke(); context.fill(); //樣式 context.fillStyle = "rgb(255,0,0)"; context.fillRect(0, 1, 20, 20); context.fillStyle = "rgb(0,255,0)"; context.fillRect(25, 1, 20, 20); context.strokeStyle = "rgb(255,0,0)"; context.strokeRect(50, 1, 20, 20); context.strokeStyle = "rgb(0,255,0)"; context.strokeRect(75, 1, 20, 20); context.strokeStyle = "rgb(0,0,255)"; context.beginPath(); context.moveTo(100, 10); context.lineTo(300, 10); context.closePath(); context.stroke(); //修改線條寬度 context.lineWidth = 5; context.strokeStyle = "rgb(255,0,0)"; context.beginPath(); context.moveTo(100, 20); context.lineTo(300, 20); context.closePath(); context.stroke(); context.lineWidth = 10; context.strokeStyle = "orange"; context.strokeRect(350, 200, 100, 100); //繪製文本(使用canvas繪製文本並非好方法) var text = "Hello World!"; context.fillStyle = "pink"; context.font = "italic 50px serif"; context.fillText(text, 10, 400); //繪製描邊文本 context.strokeStyle = "pink"; context.font = "50px serif"; context.strokeText(text, 300, 400); //擦除Canvas //context.clearRect(0, 0, canvas.width(), canvas.height()); //寬度/高度技巧 context.fillStyle = "yellow"; //重設置canvas高度寬度將完全重置canvas上所有內容為初始狀態 canvas.attr("width", canvas.width()); canvas.attr("height", canvas.height()); //將繪製黑色矩形 context.fillRect(40, 40, 100, 100); }); </script> </head> <body> <!-- 創建一個canvas元素 --> <canvas id="myCanvas" width="700" height="500"></canvas> </body> </html>