javascript - Uncaught ReferenceError : g is not defined

标签 javascript html

好吧,我刚刚做了一个计算器,在 Chrome 上测试它时,我遇到了这个错误 “ Uncaught ReferenceError :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";
}

修改后,还是一样的错误。

最佳答案

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

关于javascript - Uncaught ReferenceError : g is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24477955/

相关文章:

javascript - 有没有办法调用部分函数

asp-classic - 如何使用 eventArgs e 调用 jscript onFormSubmit()(经典的 asp)

html - 站点一侧的额外空白

html - 使用 Bootstrap img-responsive 类悬停时的 z-index

javascript - css 工具提示位置不固定

javascript - Angular 主模块 app.js 正在被缓存,需要一种方法来确保添加新代码时不会被缓存

javascript - ExtJs 4.2 - 取消/清除组件的动画链

javascript - 奇怪的数组对象 - JavaScript

javascript - Bootstrap 3 - 最大化窗口时导航对齐未正确显示

html - 通过普通的 html 链接打开 Excel 文件