第一步:html5页面中添加canvas元素
<canvas id="myCanvas" width="300" height="300"></canvas>
1、javascript绘制图形(矩形)
<script type="text/javascript"> var c=document.getElementById("myCanvas"); var cxt=c.getContext("2d"); //获取允许绘制图像的2D环境 cxt.fillStyle="#FF0000"; //fillStyle为绘制的图像填充颜色 cxt.fillRect(0,0,150,75); //fillRect绘制矩形,前两个坐标为x,y轴,后面为宽高 </script>
除了可以使用fillStyle和fillRect,还可以使用strokeStyle和strokeRect,fill是填充,而stroke是轮廓,所有用strokeStyle和strokeRect是绘制的矩形轮廓,而fillStyle与fillRect绘制的是实体矩形。
2、绘制直线(使用 moveTo、lineTo、stroke方法)
moveTo(x,y):用于建立新的子路径,规定起始点为 (x,y)
lineTo(x,y):用于从moveTo方法规定的起始点开始绘制一条到规定坐标的直线。
stroke():用于沿着该路径绘制一条直接。
<script type="text/javascript"> window.onload = function(){ var c = document.getElementById('myCanvas'); var content = c.getContext('2d'); content.moveTo(0,0); content.lineTo(300,300); content.stroke(); }; </script>
3、绘制圆形(用到beginPath、arc、closePath、fill这四个方法)
beginPath():用于开始绘制路径
closePath():用于将图形闭合起来
arc(x,y,radius,startAngle,endAngle,anticlockwise):用于绘制圆形,x,y为坐标,radius为半径,startAngle为开始的角度,endAngle为结束的半径,anticlockwise为是否按顺时针方向绘制图形。
<script type="text/javascript"> window.onload = function(){ var c = document.getElementById('myCanvas'); var content = c.getContext('2d'); content.fillStyle="#FA7E2A"; content.beginPath(); content.arc(50,50,50,0,Math.PI*2,true); content.closePath(); content.fill(); }; </script>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{padding: 0;margin:0;} body{background: #1b1b1b;} #div1{margin:50px auto; width:300px; height: 300px;} canvas{background: #fff;} </style> <script type="text/javascript"> window.onload = function(){ var c = document.getElementById('myCanvas'); var content = c.getContext('2d'); for(var i=0; i<=15; i++){ content.fillStyle = '#FA7E2A'; content.beginPath(); content.arc(0,150,i*10,0,Math.PI*3/2,true); //content.closePath(); content.stroke(); } }; </script> </head> <body> <div id="div1"> <canvas id="myCanvas" width="300" height="150"></canvas> </div> </body> </html>
4、绘制三角形
清除:clearRect(x,y,width,height); x,y为坐标
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{padding: 0;margin:0;} #div1{margin:50px auto; width:300px; height: 300px;} canvas{border:1px solid #000;} </style> <script type="text/javascript"> window.onload = function(){ var c = document.getElementById('myCanvas'); var content = c.getContext('2d'); content.fillStyle = '#FA7E2A'; content.beginPath(); content.moveTo(25,25); content.lineTo(150,25); content.lineTo(25,150); content.closePath(); content.fill(); document.getElementsByTagName('input')[0].onclick = function(){ content.clearRect(0,0,300,300); }; }; </script> </head> <body> <div id="div1"> <canvas id="myCanvas" width="300" height="300"></canvas> <input type="button" value="清除画布" /> </div> </body> </html>