我有3個x,y點,我試圖用來繪製一個正確的trangle。所以我在計算邊長之後計算三角形的角度。在獲得斜邊的長度後,我想旋轉斜邊以使其完成三角形。出於某種原因,即使旋轉了適當的度數,我的斜邊位置也有些偏離了位置。這是我的代碼和jsfiddle。繪製一個三角形的純Javascript,定位斜邊
<html>
<head>
<script>
window.onload = function() {
//drawTriangle(1,1,100,1,100,100);
drawTriangle(1,1,100,1,1,100);
}
function drawTriangle(x1, y1, x2, y2, x3, y3) {
//The length of side a is the difference between point 1 and point 2's x (horizonal) axis.
var a = Math.abs(x1 - x2);
//The length of side b is the difference between point 2 and point 3's y (veritcal axis)
var b = Math.abs(y2 - y3);
//Too find the length of the last side c, we must use the pythagorean theorem.
//c*c=a*a+b*b
//square side a and b, and add the result. Then find the square root of the result.
var c = Math.sqrt(((a*a) + (b*b)));
//We must use the Cosine rule to solve the triangles 3 angles.
//c^2 = a^2 + b^2 - c^2
var A = (Math.acos(((c*c)+(b*b)-(a*a))/(2*c*b)))*(180/Math.PI);
var B = (Math.acos(((c*c)+(a*a)-(b*b))/(2*a*c)))*(180/Math.PI);
var C = (Math.acos(((a*a)+(b*b)-(c*c))/(2*a*b)))*(180/Math.PI);
//Add side A div between points x1,y1, and x2,y2
var div = document.createElement('div');
div.style.height = '1px';
div.style.width = a + 'px';
div.style.backgroundColor = 'black';
div.style.position = "absolute";
div.style.left = x1;
div.style.top = y1;
document.body.appendChild(div);
//Add side B div between points x2,y2 and x3,y3
div = document.createElement('div');
div.style.height = b + "px";
div.style.width = "1px";
div.style.backgroundColor = 'black';
div.style.position = "absolute";
div.style.left = x2;
div.style.top = y2;
document.body.appendChild(div);
div = document.createElement('div');
div.style.height = "1px";
div.style.width = c + "px";
div.style.backgroundColor = 'black';
div.style.position = "absolute";
div.style.left = x3;
div.style.top = y3;
div.style.transform = "rotate(45deg)";
document.body.appendChild(div);
}
</script>
</head>
<body>
</body>
</html>
您必須正確設置['transform-origin'](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin)。 – Teemu 2014-10-27 18:39:17
好的,謝謝Teemu,我應該在哪裏設置轉換的起點以形成三角形。 – 2014-10-27 18:43:20
您並未設置頂部和左側的單位。將「px」添加到值中。 'div.style.left = x1 +「px」; div.style.top = y1 +「px」;' – epascarello 2014-10-27 18:45:22