如何为for循环中创建的图层创建动画

时间:2014-08-28 23:33:13

标签: framerjs

考虑Collection GridLayer with Click Animation的两个代码段。以下内容仅将动画侦听器添加到最后一个网格项(3:3位置的图层):

rows = 3
cols = 3

gutter = 16
width  = 96
height = 96

for rowIndex in [0..rows-1]
    for colIndex in [0..cols-1]

        cellLayer = new Layer
            width:  width
            height: height
            x: colIndex * (width + gutter)
            y: rowIndex * (height + gutter)

        Utils.labelLayer cellLayer, "#{rowIndex}:#{colIndex}"

        cellLayer.on Events.Click, ->
            cellLayer.animate
                properties:
                    scale: 1.4
                curve: "spring"

如何在for循环中单独命名图层以应用动画?

cellLayer[rowIndex][colIndex] = new Layer这样的东西是理想的,但不起作用。

2 个答案:

答案 0 :(得分:1)

TL;博士

只需使用do关键字就可以解决这个问题:

do (cellLayer) -> 
  cellLayer.on Events.Click, ->
    cellLayer.animate
      properties: scale: 1.4
      curve: "spring"

  

当使用JavaScript循环生成函数时,通常会插入一个闭包装,以确保循环变量被关闭,并且所有生成的函数不只是共享最终值。 CoffeeScript提供了“do”关键字,它立即调用传递的函数,转发任何参数。

从技术上讲,您必须使每个范围都为cellLayer,因为cellLayer的范围是循环的。在CoffeeScript中,提供了do关键字的语法糖。只需将do放入代码中,然后使用IIFE自动创建范围。如果您对JavaScript有所了解,transpiled code可以为您提供帮助。

答案 1 :(得分:1)

另请注意,我将单击的图层作为第二个参数添加到处理程序中:

 cellLayer.on Events.Click, (event, clickedLayer) ->
        clickedLayer.animate
            properties:
                scale: 1.4
            curve: "spring"
相关问题