如何在函数曲线 HTML 画布下查找区域

How to find area under function curve HTML Canvas

本文关键字:布下 查找 区域 HTML 曲线 函数      更新时间:2023-09-26

我必须在y=x*x曲线下找到面积,并用红色圆圈的随机分布填充该区域。到目前为止我的进步

for (x=150; x<=750; x++)
    {
            y=-1/300*(x-450)*(x-450) +470
        if (x==0)
        {
            ctx.moveTo(x,y);
        }   
        else
        {
            ctx.lineTo(x,y);
        }
    }
    ctx.stroke();

    iMax=1000
    for (i=0; i<=iMax;i++)
    {
        x=150 + Math.floor((Math.random()*600));
        y=170 + Math.floor((Math.random()*300));
        d=-1/300*(x-450)*(x-450) +470
        if(d<y)
        {
            ctx.beginPath();
            ctx.arc(x,y,2,0,2*Math.PI);
            ctx.strokeStyle = 'red';
            ctx.stroke();
        }
        else
        {
            ctx.beginPath();
            ctx.arc(x,y,2,0,2*Math.PI);
            ctx.stroke();
        }
    }

但我只是无法弄清楚如何确定曲线下方的区域,我需要帮助。

您可以使用计数积分,如下所示:

var ySum = 0;
for (x=150; x<=750; x++)
{
        y=-1/300*(x-450)*(x-450) +470;
        ySum += 470 - y - 1;// 1 is line width
    if (x==0)
    {
        ctx.moveTo(x,y);
    }   
    else
    {
        ctx.lineTo(x,y);
    }
}
alert(ySum);//area below curve
ctx.stroke();

iMax=1000
for (i=0; i<=iMax;i++)
{
    x=150 + Math.floor((Math.random()*600));
    y=170 + Math.floor((Math.random()*300));
    d=-1/300*(x-450)*(x-450) +470
    if(d<y)
    {
        ctx.beginPath();
        ctx.arc(x,y,2,0,2*Math.PI);
        ctx.strokeStyle = 'red';
        ctx.stroke();
    }
    else
    {
        ctx.beginPath();
        ctx.arc(x,y,2,0,2*Math.PI);
        ctx.stroke();
    }
}