我有这个代码可以使用,但我想改进它:
var c = canvas.getContext("2d");
//this is called as an object method I created
var animar = function () {
var obj = this;//saves the object that called it to later access to its properties
var counter= 0;
var animacion = setInterval(function(){
c.save()
c.clearRect(0, 0, canvas.width, canvas.height);
c.rotate(0.1*counter);
obj.pintar();
c.restore();
counter++;
}, 50);
}
我想使用outter功能以便将来使用,但是当我更改我的代码时,有一个提升问题,我不知道如何让计数器进入rotar()功能没有一直覆盖它:
var animar = function () {
var obj = this;
var counter= 0;
var animacion = setInterval(function(){
rotar(obj)
}, 50);
}
function rotar (obj) {
c.save()
c.clearRect(0, 0, canvas.width, canvas.height);
c.rotate(0.1*counter);
obj.pintar();
c.restore();
counter++;
}
我知道第一个是有效的,因为它们是嵌套的,而在第二个例子中则不是。如何设置setInterval 不使用全局变量的计数器? (我的意思是......如果我第二次调用它,它将不会从0开始。如果我在animar()函数中将它设置为0,它会起作用,但是我需要设置它在使用计数器或使用不同名称的计数器的每个功能中为0。这两个功能听起来不太好。) 感谢
答案 0 :(得分:2)
您只需将var counter = 0
放在函数之外:
var counter;
var animar = function () {
var obj = this;
counter = 0; // reset every time before 'animacion'...
var animacion = setInterval(function(){
rotar(obj)
}, 50);
}
function rotar (obj) {
c.save()
c.clearRect(0, 0, canvas.width, canvas.height);
c.rotate(0.1*contador);
obj.pintar();
c.restore();
counter++;
}
或者,如果您不想要全局变量,可以按照Walter的回答,或者这样做:
var animar = function () {
var obj = this;
var counter = 0; // new variable every time animar() is called
var animacion = setInterval(function(){
rotar(obj, counter);
counter++;
}, 50);
}
function rotar (obj, counter) {
c.save()
c.clearRect(0, 0, canvas.width, canvas.height);
c.rotate(0.1*contador);
obj.pintar();
c.restore();
}
答案 1 :(得分:0)
将counter
范围限定在animar
对象中:
var animar = function () {
var obj = this;
obj.counter= 0;
var animacion = setInterval(function(){
rotar(obj)
}, 50);
}
function rotar (obj) {
c.save()
c.clearRect(0, 0, canvas.width, canvas.height);
c.rotate(0.1*obj.counter);
obj.pintar();
c.restore();
obj.counter++;
}