我找到了一个API,它将使使用CANVAS更加容易。它可以很容易地选择和修改画布上的各个元素。它是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;
(功能(目标){
*位图。按=函数(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!"); } }
}
(function(target){...content...})(bitmap)
正在为内容创建一个词法作用域,以便内容中的任何var
或function
声明都不会泄漏到全局作用域中。在内容内部,target
只是bitmap
。
你可以认为这类似于
function init(target) { ...content... }
然后立即调用它,将CCD_ 5作为CCD_但第一个版本对全局作用域的干扰更小——它没有将init
定义为全局作用域中的名称。
编辑:我认为目的不是词法范围,而是确保事件处理程序指向正确的位图,而不是for循环处理的最后一个位图。init(位图);
请参阅Javascript循环中的事件处理程序-是否需要闭包?了解更多详细信息。