未被捕获的参考错误:g没有定义。

时间:2022-07-20 20:27:30

Alright so I just made a calculator, and while testing it on Chrome, I came across this error "Uncaught ReferenceError: g is not defined (anonymous function)". Even though I just defined it using

好吧,我刚做了一个计算器,在Chrome上测试时,我发现这个错误“未被发现的参考错误:g没有定义(匿名函数)”。尽管我只是用它来定义。

function chart(principal, interest, monthly, payments) {
    var graph = document.getElementById("graph");
    graph.width = graph.width;

    if (arguments.length == 0 || !graph.getContext) return;

    var g = graph.getContext("2d"); 
    //g is defined here yet on line 147, i get the          
    //error
    var width = graph.width,
        height = graph.height;

    function paymentToX(n) {
        return n * width / payments;
    }

    function amountToY(a) {
        return height - (a * height / (monthly * payments * 1.05));
    }

    g.moveTo(paymentToX(0), amountToY(0));
    g.lineTo(paymentToX(payments),
    amountToY(monthly * payments));

    g.lineTo(paymentToX(payments), amountToY(0));
    g.closePath();
    g.fillStyle = "#f88";
    g.fill();
    g.font = "bold 12px sans-serif";
    g.fillText("Total Interest Payments", 20, 20);

    var equity = 0;
    g.beginPath();
    g.moveTo(paymentToX(0), amountToY(0));
    for (var p = 1; p <= payments; p++) {
        var thisMonthsInterst = (principal - equity) * interest;
        bal -= (monthly - thisMonthsInterst);
        g.lineTo(paymentToX(p), amountToY(bal));
    }
    g.lineWidth = 3;
    g.stroke();
    g.fillStyle = "black";
    g.fillText("Loan Balance", 20, 20);

    g.textAlign = "center";
    var y = amountToY(0);
    var x = paymentToX(year * 12);
    g.fillRect(x - 0.5, y - 3, 1, 3);
    if (year == 1) g.fillText("Year", x, y - 5);
    if (year % 5 == 0 && year * 12 !== payments) g.fillText(String(year), x, y - 5);
 }
g.lineWidth = 3;
g.stroke();
g.fillStyle = "black";
g.fillText("Loan Balance", 20, 20);

g.textAlign = "center";
var y = amountToY(0);
var x = paymentToX(year * 12);
g.fillRect(x - 0.5, y - 3, 1, 3);
if (year == 1) g.fillText("Year", x, y - 5);
if (year % 5 == 0 && year * 12 !== payments) g.fillText(String(year), x, y - 5);
 g.textAlign = "right";
  g.textBaseline = "middle";
}

even after modifying it, I still had the same error.

即使修改后,仍然有相同的错误。

2 个解决方案

#1


2  

g.textAlign and g.textBaseline are outside of the function in which you defined g

g。textAlign和g。文本基线超出了定义g的函数。

#2


0  

The function chart ends before g.lineWidth = 3. Everything beyond this point has no definition of g.

函数图在g之前结束。线宽= 3。除了这个点之外的所有东西都没有g的定义。

#1


2  

g.textAlign and g.textBaseline are outside of the function in which you defined g

g。textAlign和g。文本基线超出了定义g的函数。

#2


0  

The function chart ends before g.lineWidth = 3. Everything beyond this point has no definition of g.

函数图在g之前结束。线宽= 3。除了这个点之外的所有东西都没有g的定义。