html5绘制三角形并填充,html5画布三角形按百分比填充颜色

三角形和区域

求解分数(p)(0-1)给出三角形(w)宽度和(h)高度的新高度(h1)

三角形区域是

w * h * 0.5

切割三角形会得到一个三角形和一个梯形。

我们将解决分数区域是梯形的区域。

以三角形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)* h1 2

这给出了二次方的一般形式是ax 2 + bx + c = 0(在这种情况下,未知值x是h1梯形的高度),可以用(-b)求解(+/-)sqrt(b 2 - 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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值