HTML5图形绘制
要在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。
};
我超爱学习的