I am very new in JavaScript. I want to develop a canvas animation to run on Blackberry. For that I would like to use HTML5 and JavaScript. I want to create the following functions:
funct开发者_开发百科ion
drawCircle()
. The center of the circle will be the center of the canvas (the size of the canvas will be the size of the window), the radius will be enter by the user. Up to here, where should I declare the canvas in order to assign the center of the circle?function
draw()
which will all functions which draw shapes. Then will be called in the init function.function
init()
. Which will draw the shapes at a set of interval.
Where should I declare these?:
var canvas = document.getElementById()
var context = canvas.getContext()
canvas.width = windows.innerWidh
Any javascript variable defined in the global scope (i.e. not in a function or class) is accessible from the rest of the code.
var testVariable = "test";
function test() {
console.log(testVariable);
}
test();
Alternatively (and it's frowned upon as bad practice) declaring a variable without the var
modifier from outside the global scope puts it in the global scope:
function test() {
testVariable = "test";
}
test();
console.log(testVariable);
edit:
As the comment rightly points out:
Global variables and functions are rarely required. Using globals may cause naming conflicts between javascript source files and cause code to break. For this reason, it is a good practice to encapsulate functionality within a single global namespace...The simplest approach is to create a single global object and assign properties and methods to this object.
Creating A Namespace:
var MyLib = {}; // global Object cointainer
MyLib.value = 1;
MyLib.increment = function() { MyLib.value++; }
MyLib.show = function() { alert(MyLib.value); }
MyLib.value=6;
MyLib.increment();
MyLib.show(); // alerts 7
Here's a description of what a namespace is.
精彩评论