简体   繁体   中英

Uncaught ReferenceError: g is not defined

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

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.

g.textAlign和g.textBaseline在定义g的函数之外

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM