S.Drawing = (function () {
var canvas,
context,
renderFn
requestFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
return {
init: function (el) {
canvas = document.querySelector(el);
context = canvas.getContext('2d');
this.adjustCanvas();
window.addEventListener('resize', function (e) {
S.Drawing.adjustCanvas();
});
},
loop: function (fn) {
renderFn = !renderFn ? fn : renderFn;
this.clearFrame();
renderFn();
requestFrame.call(window, this.loop.bind(this));
},
adjustCanvas: function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
},
clearFrame: function () {
context.clearRect(0, 0, canvas.width, canvas.height);
},
getArea: function () {
return { w: canvas.width, h: canvas.height };
},
drawCircle: function (p, c) {
context.fillStyle = c.render();
context.beginPath();
context.arc(p.x, p.y, p.z, 0, 2 * Math.PI, true);
context.closePath();
context.fill();
}
}
}());
这是一整块代码
其中这一块是什么语法啊。。。我见过好几次但是一直没明白,原谅我菜。。。
init: function (el)
loop: function (fn)
adjustCanvas: function ()
...
针对这些
init: function (el) {
canvas = document.querySelector(el);
context = canvas.getContext('2d');
this.adjustCanvas();
window.addEventListener('resize', function (e) {
S.Drawing.adjustCanvas();
});
},
loop: function (fn) {
renderFn = !renderFn ? fn : renderFn;
this.clearFrame();
renderFn();
requestFrame.call(window, this.loop.bind(this));
},
adjustCanvas: function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
},
clearFrame: function () {
context.clearRect(0, 0, canvas.width, canvas.height);
},
getArea: function () {
return { w: canvas.width, h: canvas.height };
},
drawCircle: function (p, c) {
context.fillStyle = c.render();
context.beginPath();
context.arc(p.x, p.y, p.z, 0, 2 * Math.PI, true);
context.closePath();
context.fill();
}
}
希望帮忙解释下,还有就是这个语法,最好帮忙链个文档页我去参考学习下,谢谢!
整体上是个赋值语句。
赋值表达式右侧所有代码封装在一个立即执行函数内。
立即执行函数里面,首先定义了
canvas
、context
等局部变量,在这里你可以叫它们私有变量。然后函数构造了一个比较复杂的对象作为返回值,也就是return
后面的大括号中的部分。对象中定义了很多属性,例如
init
、loop
等。由于它们的值都是函数,所以这些属性可以称为方法。最后,立即执行函数被调用,返回了那个对象,然后赋值给了一开始的
S.Drawing
变量。至于你截取的那块,就是用对象字面量的形式来定义一个对象。
比如我可以这样定义一个东西:
上面这个很好理解吧?那么我把上面的
'Tom'
和12
换成一个函数呢?那就成了你提问中的形式了。记住: