canvas常用画法整理
代码Canvas.htm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | <!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> |
运行效果:三角和圆弧
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步