HTML5圖形繪制
阿新 • • 發佈:2017-07-11
ctype 染色 blog col lac span 路徑 ready 圓形
要在HTML5中繪制圖形,首先要放置一個canvas元素
<canvas id="canvas" width="400" height="300"/>
canvas的代碼實際上是放在JavaScript腳本中的,因此,要先獲得該元素的id
var canvas =document.getElementById("canvas"); if (canvas==null) return false; var context=canvas.getContext("2d"); context.fillStyle="#eeeeff"; context.fillRect(0,0,400,300); context.fillStyle="red"; context.strokeStyle="blue"; context.lineWidth=1; context.fillRect(50,50,1001,100); context.strokeRect(50,50,100,100);
全部代碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>example for html5</title> </head> <body> <div class="showmore"> <a title="這是一個提示" id="tipping">tips</a> <canvas id="canvas" width="400" height="300"/> </div> <script type="text/javascript"> var canvas =document.getElementById("canvas"); if (canvas==null) alert("null"); var context=canvas.getContext(‘2d‘); context.fillStyle="#eeeeff"; context.fillRect(0,0,400,300); context.fillStyle="red"; context.strokeStyle="blue"; context.lineWidth=1; context.fillRect(50,50,100,100); context.strokeRect(50,50,100,100); </script> </body> </html>
最近也在學習jQuery,那麽在jQuery中如何繪制canvas呢?要註意的是,jQuery對象不能直接使用canvas中的方法,因此首先要把jQuery對象轉化成dom對象,才能進行繪圖,當然,代碼其實沒有簡便多少
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>example for html5</title> <script src="jquery.js" type="text/javascript"></script> </head> <body> <div class="showmore"> <a title="這是一個提示" id="tipping">tips</a> <canvas id="canvas" width="400" height="300"/> </div> <script type="text/javascript"> $(document).ready(function(){ var canvas=$("#canvas")[0]; if (canvas==null) alert("null"); var context=canvas.getContext(‘2d‘); context.fillStyle="#eeeeff"; context.fillRect(0,0,400,300); context.fillStyle="red"; context.strokeStyle="blue"; context.lineWidth=1; context.fillRect(50,50,100,100); context.strokeRect(50,50,100,100); }); </script> </body> </html>
繪制圓形
for(var i=0;i<8;i++){ context.beginPath(); context.arc(25*i,25*i,i*10,0,Math.PI*2,true); context.closePath(); context.fillStyle=‘rgba(255,0,0,0.25)‘; context.fill(); }
繪制直線
context.beginPath(); //路徑開始點,設置這個點主要是為了防止後續染色影響前面部分
context.strokeStyle="black"; //設置直線的粗細和顏色
context.lineWidth=10;
context.moveTo(20,20); //設置直線起點,終點
context.lineTo(30,100);
context.stroke(); //繪制
載入圖片
var image=new Image();
image.src="1.png";
image.onload=function(){
context.drawImage(image,20,20,20,20); //分別是圖形對象,繪制起點x,y,圖像大小w,h。
};
HTML5圖形繪制