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.
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.