三角形和面积
求解分数 (p) (0-1) 以给出三角形 (w) 宽度和 (h) 高度的新高度 (h1)
三角形的面积是
切割三角形会得到一个三角形和一个梯形。
我们将求解使得分数面积是梯形的面积。
以三角形 w、h 和 h1 表示的梯形面积(尖端的另一端),其中 h1 是梯形的未知高度。
- a1 = w * h1 - (w / 2 * h) * h1 * h1
h1 * h1 表示此解是二次解,因此请制定一个等于 0 的公式。我们知道梯形的面积是三角形面积乘以分数,因此使用 (w * h * 0.5 * p)并用 h1 减去上述面积解,得到
- 0 = w * h * 0.5 * p - w * h1 - (w / 2 * h) * h12
这给出了一个二次方程,一般形式是 ax2 + bx + c = 0(在这种情况下,未知值 x 是 h1 梯形的高度)可以用 (-b (+/-) sqrt(b2 - 4ac) ) / 2a。由于解决方案中的 (+/-) 有两个答案,现阶段不知道哪个答案是正确的。
因此我们需要 a,b,c 来解决
- a = w/(2*h)
- b = - w
- c = w * h * 0.5 * p
所以作为一个函数
// return the height of the trapezoid made from a triangle of width height that
// has an area equal to the area of the triangle * fraction
function getFractionHeightOfTriangle(width,height,fraction){
var a = width / (2 * height);
var b = -width;
var c = width * height * 0.5 * fraction;
// find the two solutions
var h1_a = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
var h1_b = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
// from experiment the solution is the second one
// or you can check which is positive and return that
return h1_b;
}
以顶部为原点绘制三角形
// x,y is the top (pointy end) w is width h is height
// col is stroke colour, col1 is fillColour
// lineW is line width.
var drawTriangle = function(x,y,w,h,col,col1,lineW){
ctx.beginPath();
ctx.strokeStyle = col;
ctx.fillStyle = col1;
ctx.lineWidth = lineW;
ctx.moveTo(x,y );
ctx.lineTo(x + w / 2 ,y + h);
ctx.lineTo(x - w / 2 ,y + h);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
绘制三角形的一部分
// See above function for x,y,w,h,col,col1,lineW
// which is == "top" for pointy end and != "top" for trapezoid
// amount is the height of the top
var drawPartTriangle = function(x,y,w,h,which,amount,col,col1,lineW){
ctx.beginPath();
ctx.strokeStyle = col;
ctx.fillStyle = col1;
ctx.lineWidth = lineW;
if(which === "top"){
ctx.moveTo(x,y);
ctx.lineTo(x + w / 2 * (amount / h),y + amount);
ctx.lineTo(x - w / 2 * (amount / h),y + amount);
}else{
ctx.moveTo(x + w / 2 * (amount / h),y + amount);
ctx.lineTo(x + w / 2 ,y + h);
ctx.lineTo(x - w / 2 ,y + h);
ctx.lineTo(x - w / 2 * (amount / h),y + amount);
}
ctx.closePath();
ctx.fill();
ctx.stroke();
}