纸飞机模拟一个物体在规定设计轴线偏离方位。
1 //三角形 2 function DrawTriangle(canvas, A, B, C) { 3 //画个三角形,“A、B、C”是顶点 4 with (canvas) { 5 moveTo(A[0], A[1]); 6 lineTo(B[0], B[1]); 7 lineTo(C[0], C[1]); 8 lineTo(A[0], A[1]); 9 } 10 } 11 12 // 画纸飞机 13 //headx,heady 纸飞机头坐标 14 //footx,footy 纸飞机尾巴坐标 15 function DrawDarts(canvas, headx, heady, footx, footy) { 16 var c = document.getElementById(canvas); 17 var cxt = c.getContext("2d"); 18 19 //半径 R 20 var R = 150; 21 22 //转换头坐标 23 var headx1 = R + headx; 24 var heady1 = R - heady; 25 //转换尾坐标 26 var footx1 = R + footx; 27 var footy1 = R - footy; 28 29 //左尾 30 var footxl = R + (footx - 50); 31 var footyl = R - footy; 32 33 //右尾 34 var footxr = R + (footx + 50); 35 var footyr = R - footy; 36 37 //上尾 38 var footxu = R + footx; 39 var footyu = R - (footy - 50); 40 41 //下尾 42 var footxd = R + footx; 43 var footyd = R - (footy + 50); 44 45 46 //判断头x和尾x的大小 47 cxt.beginPath(); 48 cxt.strokeStyle = "black"; 49 cxt.fillStyle = "#6C8D9F"; 50 var A = new Array(headx1, heady1); 51 var B = new Array(footx1, footy1); 52 // alert(headx1); 53 // alert(footx1); 54 if (parseInt(headx1) - parseInt(footx1) <= 0) 55 var C = new Array(footxr, footyr); 56 else 57 var C = new Array(footxl, footyl); 58 DrawTriangle(cxt, A, B, C); 59 60 cxt.fill(); 61 cxt.closePath(); 62 cxt.stroke(); 63 64 //画头、上、下尾巴 形成的三角形 65 cxt.beginPath(); 66 cxt.strokeStyle = "black"; 67 cxt.fillStyle = "#6C8D9F"; 68 var A1 = new Array(headx1, heady1); 69 var B1 = new Array(footxu, footyu); 70 var C1 = new Array(footxd, footyd); 71 DrawTriangle(cxt, A1, B1, C1); 72 cxt.fill(); 73 cxt.closePath(); 74 cxt.stroke(); 75 76 cxt.beginPath(); 77 cxt.strokeStyle = "black"; 78 cxt.fillStyle = "#6C8D9F"; 79 var A2 = new Array(headx1, heady1); 80 var B2 = new Array(footx1, footy1); 81 if (parseInt(headx1) - parseInt(footx1) <= 0) 82 var C2 = new Array(footxl, footyl); 83 else 84 var C2 = new Array(footxr, footyr); 85 DrawTriangle(cxt, A2, B2, C2); 86 cxt.fill(); 87 cxt.closePath(); 88 cxt.stroke(); 89 }
html 页面调用
<!DOCTYPE HTML> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>HTML Canvas 画纸飞机</title> <script type="text/javascript" src="Darts.js"></script> </head> <body><canvas id="can" width="300" height="300" style="border: 1px solid #00F">浏览器不支持HTML5!</canvas><script type="text/javascript" charset="utf-8">DrawDarts("can", -10, 10, 30, -30)</script> </body> </html>
预览效果图
效果图2: