canvas常用画法整理
代码Canvas.htm
<!DOCTYPE html> <html lang="en"> <head> <title>canvas简单应用画各种图形状</title> </head> <!--<script language="javascript" src="jquery-1.8.3.js"></script>--> <script language="javascript" type="text/javascript"> //通过画线段构造三角形 function draw_triangle(x1,y1,x2,y2,x3,y3){ var c = document.getElementById("canvas1"); var cxt = c.getContext("2d"); cxt.moveTo(x1,y1); cxt.lineTo(x2,y2); cxt.lineTo(x3,y3); cxt.lineTo(x1,y1); cxt.stroke(); } //画三角进一步封装 function draw(){ draw_triangle(100,50,300,200,150,100); } //向canvas原型对象添加画扇形方法 CanvasRenderingContext2D.prototype.selector=function(x,y,radius,sDeg,eDeg){ //保存初始状态 this.save(); // 位移到目标点 this.translate(x, y); this.beginPath(); // 画出圆弧 this.arc(0,0,radius,sDeg, eDeg); // 再次保存以备旋转 this.save(); // 旋转至起始角度 this.rotate(eDeg); // 移动到终点,准备连接终点与圆心 this.moveTo(radius,0); // 连接到圆心 this.lineTo(0,0); // 还原 this.restore(); // 旋转至起点角度 this.rotate(sDeg); // 从圆心连接到起点 this.lineTo(radius,0); this.closePath(); // 还原到最初保存的状态 this.restore(); return this; } function b(){ var c = document.getElementById("canvas1"); var cxt = c.getContext("2d"); //画线 /**cxt.moveTo(10,10); cxt.lineTo(60,80); cxt.stroke();**/ //画图片 /*cxt.beginPath(); var img = new Image(); img.src = 'b.jpg'; img.onload=function(){ cxt.drawImage(img,0,0);*/ //画圆环 /*cxt.clearRect(0,0,1200,400); cxt.beginPath(); cxt.arc(300,100,60,Math.PI*2,false); cxt.closePath(); cxt.fill(); cxt.fillStyle="white"; cxt.beginPath(); cxt.arc(300,100,50,Math.PI*2,false); cxt.closePath(); cxt.fill();*/ //画圆弧 cxt.selector(100,100,50,0,Math.PI*0.75); } </script> <body onload="b();"> <!--<canvas id="cans" width="500px" height="300px" style="border:1px solid red;">浏览器不支持canvas</canvas>--> <canvas id="canvas1" width="1200" height="400" style="border:1px solid red">浏览器不支持该功能</canvas> <button onclick="draw()">start</button> </body> </html>
运行效果:三角和圆弧