三角形の外接円を求める
by abbcd
HTML
<canvas id="can"></canvas>
CSS
#can {
background: #efefef;
}
JavaScript
$(document).ready(function () {
var SAMPLE = {};
SAMPLE.Main = (function () {
// 頂点
function Vertex(x, y) {
this.x = x;
this.y = y;
}
// 三角形
function Triangle(v0, v1, v2) {
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
// 三角形を描画
this.draw = function () {
var drawLine = function (vs, vd) {
// パスのリセット
ctx.beginPath();
// 線の太さ
ctx.lineWidth = 1;
// 線の色
ctx.strokeStyle = "#454545";
// 開始位置
ctx.moveTo(vs.x, vs.y);
// 次の位置
ctx.lineTo(vd.x, vd.y);
// 描画
ctx.stroke();
};
drawLine(this.v0, this.v1);
drawLine(this.v1, this.v2);
drawLine(this.v2, this.v0);
};
// 外接円を描画
this.drawCircle = function () {
// 外接円の求め方
var x1 = this.v0.x,
y1 = this.v0.y,
x2 = this.v1.x,
y2 = this.v1.y,
x3 = this.v2.x,
y3 = this.v2.y,
c = 2.0 * ((x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)),
x = ((y3 - y1) * (x2 * x2 - x1 * x1 + y2 * y2 - y1 * y1) + (y1 - y2) * (x3 * x3 - x1 * x1 + y3 * y3 - y1 * y1)) / c,
y = ((x1 - x3) * (x2 * x2 - x1 * x1 + y2 * y2 - y1 * y1) + (x2 - x1) * (x3 * x3 - x1 * x1 + y3 * y3 - y1 * y1)) / c,
center = new Vertex(x, y), // 外接円の中心
dx = center.x - v0.x,
dy = center.y - v0.y,
radius = Math.sqrt((dx * dx) + (dy * dy)), // 外接円の半径
circle = new Circle(center, radius);
...