简体   繁体   中英

Global variables issue in my JavaScript file

  1. Why does the alert("2") pop up first?
  2. Why can't I create global variables c and ctx?
  3. How do I create these two global variables so I can use them in another function eg drawCircle();

     //html5 //<script type="text/javascript" src="my.js"></script> // ... //<canvas id="can" width="500" height="500></canvas> //my.js //The working code window.onload = drawRectangle; function drawRectangle() { var c = document.getElementById("can"); var ctx = c.getContext("2d"); ctx.fillStyle = "green"; ctx.fillRect(50, 50, 200, 100); } //my.js //The non-working code //alert function just for debugging window.onload = init; var c; var ctx; function init() { alert("1"); c = document.getElementById("can"); ctx = c.getContext("2d"); } function drawRectangle() { alert("2"); ctx.fillStyle = "green"; ctx.fillRect(50, 50, 200, 100); } drawRectangle();

    If I create c and ctx as global variables in the same HTML5 file, and it works as it should. Why does not work on an external javascript file?

You are calling drawRectangle() before init has run. It uses the global variables as expected, but they are still uninitialised. Move the call into the init function:

var c;
var ctx;
function init() {
    alert("1");
    c = document.getElementById("can");
    ctx = c.getContext("2d");
    drawRectangle();
//  ^^^^^^^^^^^^^^^^
}
function drawRectangle() {
    alert("2");
    ctx.fillStyle = "green";
    ctx.fillRect(50, 50, 200, 100);
}
window.onload = init;

After doing that, you can (and should) avoid the global variables and simply pass the necessary values by argument:

function init() {
    var c = document.getElementById("can");
    var ctx = c.getContext("2d");
    drawRectangle(ctx);
//                ^^^
}
function drawRectangle(ctx) {
//                     ^^^
    ctx.fillStyle = "green";
    ctx.fillRect(50, 50, 200, 100);
}
window.onload = init;

After a few days reading, the following are explanations why the rectangle will not be drawn.

  1. While loading the page, drawRectangle() is invoked. However, variables c and ctx have not been initialized. Therefore, it will not draw the rectangle.
  2. Until finished loading the page, init() function is invoked, the variables c and ctx have also not been initialized. As a result, the rectangle will not be drawn.

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