首先看一下三角函数相关的计算,
● 已知一个锐角,求sin、cos、tan,即相对这个角的边的比例关系;
● 已知边的比例关系,arcsin、arccos、arctan,求相关锐角的角度。
1 2 3 4 5 6 7 |
sinA = Math.sin(A * Math.PI / 180) // Math.sin的参数是弧度 cosA = Math.cos(A * Math.PI / 180) // 角度A*PI/180转为对应弧度 tanA = Math.tan(A * Math.PI / 180) A = arcsin(b/c) = Math.asin(b/c) * 180 / Math.PI // Math.asin得到的是弧度 A = arccos(a/c) = Math.acos(a/c) * 180 / Math.PI // 弧度*180/PI得到的对应角的角度 A = arctan(b/a) = Math.atan(b/a) * 180 / Math.PI |
再看JavaScript中的math相关api,反正切函数atan和atan2都可以根据点x、y轴位置求出与x轴夹角。
区别是atan2能够很好的区分点在哪个象限。
代码:
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 |
<body> <canvas id="canvas" style="border:1px solid red;"></canvas> <p id="textview"></p> <script> window.onload = function () { new MouseClickListener(); }; class MouseClickListener { constructor() { this.textview = document.getElementById("textview"); this.canvas = document.getElementById('canvas'); this.canvas.width = 300; this.canvas.height = 300; this.paint = this.canvas.getContext('2d'); this.drawCross(); this.canvas.addEventListener("mousemove", this.moveCallback.bind(this)); } drawCross(){ this.paint.moveTo(0, 150); this.paint.lineTo(300, 150); this.paint.moveTo(150, 0); this.paint.lineTo(150, 300); this.paint.stroke(); } moveCallback(event) { let mx = event.clientX; // 相对于document的位置 let my = event.clientY; let rect = this.canvas.getBoundingClientRect(); // 这里无需再考虑margin let x = mx - rect.left; let y = my - rect.top; let dx = x - 150; let dy = y - 150; let a = Math.atan(dy / dx) * 180 / Math.PI; // 1、3象限都是正数,2、4象限都是负数 a = Math.atan2(dy, dx) * 180 / Math.PI; // 1->2象限是连续正数,4->3象限是连续负数 this.textview.innerHTML = "<br/>canvas上鼠标位置 x=" + x + ", y=" + y + ", 偏移x轴角度=" + a; this.paint.clearRect(0, 0, 300, 300); this.drawCross(); this.paint.beginPath(); this.paint.moveTo(x, y); this.paint.lineTo(150, 150); this.paint.stroke(); this.paint.strokeText(a, x, y); } } </script> </body> |
- end
声明
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/3619.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设