canvas笔记-画三角形并计算其外心(含算法其他绘图框架类似)
生活随笔
收集整理的這篇文章主要介紹了
canvas笔记-画三角形并计算其外心(含算法其他绘图框架类似)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
程序運行截圖如下:
源碼如下:
<!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("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)
總結
以上是生活随笔為你收集整理的canvas笔记-画三角形并计算其外心(含算法其他绘图框架类似)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++笔记-Qt中使用Lambda时[]
- 下一篇: Python笔记-UiSelector坐