Created
January 29, 2011 13:22
-
-
Save noonat/801821 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<canvas id="canvas" width="480" height="480"></canvas> | |
<script type="text/javascript"> | |
var canvas = document.getElementById('canvas'); | |
var context = canvas.getContext('2d'); | |
context.strokeStyle = '#fff'; | |
context.fillStyle = '#000'; | |
context.fillRect(0, 0, 480, 480); | |
var a, b, c, dx, dy, D, E, F; | |
a = {x: 100, y: 300}; | |
b = {x: 300, y: 300}; | |
c = {x: 150, y: 100}; | |
// making some assumptions, since we are already | |
// supposed to know these edge lengths | |
dx = c.x - a.x; | |
dy = c.y - a.y; | |
D = Math.sqrt(dx * dx + dy * dy); | |
dx = c.x - b.x; | |
dy = c.y - b.x; | |
E = Math.sqrt(dx * dx + dy * dy); | |
F = b.x - a.x; | |
// draw the triangle in white | |
context.beginPath(); | |
context.moveTo(a.x, a.y); | |
context.lineTo(b.x, b.y); | |
context.lineTo(c.x, c.y); | |
context.lineTo(a.x, a.y); | |
context.closePath(); | |
context.strokeStyle = '#fff'; | |
context.stroke(1); | |
// now try to recalculate using the edges | |
// for a right triangle: http://bit.ly/eKoiov | |
// adjacent = cos(A) * hypotenuse | |
// opposite = sin(A) * hypotenuse | |
var angleDF = Math.acos((D*D + F*F - E*E) / (2*D*F)); | |
var adjacentLength = Math.cos(angleDF) * D; | |
var oppositeLength = Math.sin(angleDF) * D; | |
var abNormal = { | |
x: b.x - a.x, | |
y: b.y - a.y | |
}; | |
var length = Math.sqrt(abNormal.x * abNormal.x + abNormal.y * abNormal.y); | |
abNormal.x /= length; | |
abNormal.y /= length; | |
// midpoint from a to b | |
var m = { | |
x: a.x + abNormal.x * adjacentLength, | |
y: a.y + abNormal.y * adjacentLength | |
}; | |
// normal from m to c is perpendicular | |
var mcNormal = { | |
x: abNormal.y, | |
y: -abNormal.x | |
}; | |
var c2 = { | |
x: m.x + mcNormal.x * oppositeLength, | |
y: m.y + mcNormal.y * oppositeLength | |
}; | |
// draw our calculated triangle in red | |
context.beginPath(); | |
context.moveTo(a.x, a.y); | |
context.lineTo(b.x, b.y); | |
context.lineTo(c2.x, c2.y); | |
context.lineTo(a.x, a.y); | |
context.closePath(); | |
context.strokeStyle = '#f00'; | |
context.stroke(1); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment