关键词搜索

源码搜索 ×
×

canvas笔记-画三角形并计算其外心(含算法其他绘图框架类似)

发布2020-06-10浏览1040次

详情内容

程序运行截图如下:

源码如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto;">
  9. 当前浏览器不支持canvas
  10. </canvas>
  11. <script>
  12. window.onload = function(){
  13. let canvas = document.getElementById("canvas");
  14. canvas.width = 800;
  15. canvas.height = 800;
  16. let context = canvas.getContext("https://cdn.jxasp.com:9143/image/2d");
  17. context.save();
  18. drawTriangle({x1: 150, y1: 20, x2: 100, y2: 200, x3: 410, y3: 260, ctx: context});
  19. context.restore();
  20. }
  21. function drawTriangle({x1, y1, x2, y2, x3, y3, rotate, ctx}){
  22. //不能让x都处于一个点上
  23. //不能让y都处于一个点上
  24. if((x1 == x2 == x3) || (y1 == y2 == y3)){
  25. return;
  26. }
  27. let posArray = [];
  28. if(y1 != y2 && posArray.length < 2){
  29. let pos = getMedLinePos({x0: x1, y0: y1, x1: x2, y1: y2});
  30. posArray.push(pos);
  31. }
  32. if(y2 != y3 && posArray.length < 2){
  33. let pos = getMedLinePos({x0: x2, y0: y2, x1: x3, y1: y3});
  34. posArray.push(pos);
  35. }
  36. if(y1 != y3 && posArray.length < 2){
  37. let pos = getMedLinePos({x0: x1, y0: y1, x1: x3, y1: y3});
  38. posArray.push(pos);
  39. }
  40. let center = getPosByTwoLine({x0: posArray[0][0].x, y0: posArray[0][0].y, x1: posArray[0][1].x, y1: posArray[0][1].y,
  41. x2: posArray[1][0].x, y2: posArray[1][0].y, x3: posArray[1][1].x, y3: posArray[1][1].y});
  42. ctx.beginPath();
  43. ctx.arc(center.x, center.y, 2, 0, Math.PI * 2);
  44. ctx.fill();
  45. ctx.beginPath();
  46. ctx.moveTo(x1, y1);
  47. ctx.lineTo(x2, y2);
  48. ctx.lineTo(x3, y3);
  49. ctx.lineTo(x1, y1);
  50. ctx.stroke();
  51. }
  52. /*求两直线的交点*/
  53. function getPosByTwoLine({x0, y0, x1, y1, x2, y2, x3, y3}){
  54. let k1 = (y0 - y1) / (x0 - x1);
  55. let k2 = (y2 - y3) / (x2 - x3);
  56. let x = (k1 * x0 - k2 * x2 + y2 - y0) / (k1 - k2);
  57. let y = y0 + (x - x0) * k1;
  58. return {x, y};
  59. }
  60. /*求两点之间中垂线 中的2个点*/
  61. function getMedLinePos({x0, y0, x1, y1}){
  62. let pos = [];
  63. let A = 2 * (x1 - x0);
  64. let B = 2 * (y1 - y0);
  65. let C = (Math.pow(x0, 2) - Math.pow(x1, 2)) + (Math.pow(y0, 2) - Math.pow(y1, 2));
  66. //随便搞2个点
  67. let newX1, newX2, newY1, newY2;
  68. newX1 = 1;
  69. newY1 = (-C - (A * 1)) / B;
  70. newX2 = 2;
  71. newY2 = (-C - (A * 2)) / B;
  72. let object1 = {x: newX1, y: newY1};
  73. let object2 = {x: newX2, y: newY2};
  74. pos.push(object1);
  75. pos.push(object2);
  76. return pos;
  77. }
  78. </script>
  79. </body>
  80. </html>

这里有几个小算法

第一个是求两点之间的中垂线:

点1为x1,y1,点2为x2,y2

中垂线一般表达式为:Ax + By + C = 0

A = 2 * (x2 - x1)

B = 2 * (y2 - y1)

C = (x1^2 + x2^2) + (y1^2 - y2^2)

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载