程序运行截图如下:
源码如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
-
- <canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto;">
- 当前浏览器不支持canvas
- </canvas>
-
- <script>
-
- window.onload = function(){
-
- let canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 800;
- let context = canvas.getContext("https://cdn.jxasp.com:9143/image/2d");
-
- context.save();
- drawTriangle({x1: 150, y1: 20, x2: 100, y2: 200, x3: 410, y3: 260, ctx: context});
- context.restore();
-
- }
-
- function drawTriangle({x1, y1, x2, y2, x3, y3, rotate, ctx}){
-
- //不能让x都处于一个点上
- //不能让y都处于一个点上
- if((x1 == x2 == x3) || (y1 == y2 == y3)){
-
- return;
- }
-
- let posArray = [];
- if(y1 != y2 && posArray.length < 2){
-
- let pos = getMedLinePos({x0: x1, y0: y1, x1: x2, y1: y2});
- posArray.push(pos);
- }
- if(y2 != y3 && posArray.length < 2){
-
- let pos = getMedLinePos({x0: x2, y0: y2, x1: x3, y1: y3});
- posArray.push(pos);
- }
- if(y1 != y3 && posArray.length < 2){
-
- let pos = getMedLinePos({x0: x1, y0: y1, x1: x3, y1: y3});
- posArray.push(pos);
- }
-
-
- let center = getPosByTwoLine({x0: posArray[0][0].x, y0: posArray[0][0].y, x1: posArray[0][1].x, y1: posArray[0][1].y,
- x2: posArray[1][0].x, y2: posArray[1][0].y, x3: posArray[1][1].x, y3: posArray[1][1].y});
-
- ctx.beginPath();
- ctx.arc(center.x, center.y, 2, 0, Math.PI * 2);
- ctx.fill();
-
- ctx.beginPath();
- ctx.moveTo(x1, y1);
- ctx.lineTo(x2, y2);
- ctx.lineTo(x3, y3);
- ctx.lineTo(x1, y1);
- ctx.stroke();
- }
-
-
- /*求两直线的交点*/
- function getPosByTwoLine({x0, y0, x1, y1, x2, y2, x3, y3}){
-
- let k1 = (y0 - y1) / (x0 - x1);
- let k2 = (y2 - y3) / (x2 - x3);
- let x = (k1 * x0 - k2 * x2 + y2 - y0) / (k1 - k2);
- let y = y0 + (x - x0) * k1;
-
- return {x, y};
- }
-
- /*求两点之间中垂线 中的2个点*/
- function getMedLinePos({x0, y0, x1, y1}){
-
- let pos = [];
- let A = 2 * (x1 - x0);
- let B = 2 * (y1 - y0);
- let C = (Math.pow(x0, 2) - Math.pow(x1, 2)) + (Math.pow(y0, 2) - Math.pow(y1, 2));
-
- //随便搞2个点
- let newX1, newX2, newY1, newY2;
- newX1 = 1;
- newY1 = (-C - (A * 1)) / B;
-
- newX2 = 2;
- newY2 = (-C - (A * 2)) / B;
-
- let object1 = {x: newX1, y: newY1};
- let object2 = {x: newX2, y: newY2};
- pos.push(object1);
- pos.push(object2);
-
- return pos;
- }
-
-
- </script>
-
-
- </body>
- </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)