我找到了一个能够更轻松地使用CANVAS的API。它允许非常容易地选择和修改画布上的各个元素。这是EaselJS。 API文档在这里。 http://easeljs.com/docs/
到目前为止,我对API很满意。令我困惑的是其中有些javascript。粗体或* *内的部分(无法使格式化工作) 这是什么样的javascript结构?
(功能(目标){...内容...})(位图) 在内容中,它引用了位图,这是外部的东西。
这是代码
for(var i = 0; i < 100; i++){
bitmap = new Bitmap(image);
container.addChild(bitmap);
bitmap.x = canvas.width * Math.random()|0;
bitmap.y = canvas.height * Math.random()|0;
bitmap.rotation = 360 * Math.random()|0;
bitmap.regX = bitmap.image.width/2|0;
bitmap.regY = bitmap.image.height/2|0;
bitmap.scaleX = bitmap.scaleY = bitmap.scale = Math.random()*0.4+0.6;
bitmap.mouseEnabled = true;
bitmap.name = "bmp_"+i;
(功能(目标){
* bitmap.onPress = function(evt)*
{if (window.console && console.log) { console.log("press!"); }
target.scaleX = target.scaleY = target.scale*1.2;
container.addChild(target);
// update the stage while we drag this target
//Ticker provides a central heartbeat for stage to listen to
//At each beat, stage.tick is called and the display list re-rendered
Ticker.addListener(stage);
var offset = {x:target.x-evt.stageX, y:target.y-evt.stageY};
evt.onMouseMove = function(ev) {
target.x = ev.stageX+offset.x;
target.y = ev.stageY+offset.y;
if (window.console && console.log) { console.log("move!"); }
}
evt.onMouseUp = function() {
target.scaleX = target.scaleY = target.scale;
// update the stage one last time to render the scale change, then stop updating:
stage.update();
Ticker.removeListener(stage);
if (window.console && console.log) { console.log("up!"); }
}
**}})(位图); **
bitmap.onClick = function() { if (window.console && console.log) { console.log("click!"); } }
}
答案 0 :(得分:1)
(function(target){...content...})(bitmap)
正在为内容创建词法范围,以便内容中的任何var
或function
声明不会泄漏到全局范围中。在内容中,target
只是另一个名称
bitmap
。
您可以将此视为与
类似function init(target) { ...content... }
然后立即调用bitmap
作为target
参数的实际值
但是第一个版本甚至更少地干扰了全局范围 - 它没有将init
定义为全局范围内的名称。
编辑: 我认为目的不是词法范围,而是确保事件处理程序指向正确的位图,而不是for循环处理的最后一个位图。 INIT(位图);
有关详细信息,请参阅Event handlers inside a Javascript loop - need a closure?。