andrewsteele
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # After Effects expressions ## Controls ### Cascading properties from a control layer to the current layer AE’s frustrating lack of global variables means that it’s sometimes necessary to cascade eg a slider control from a master control null layer to the current layer. The advantage of this is that you can then copy and paste expressions between layers that need to behave in the same way. For example, if you wanted the speed of two planets, Mercury and Venus, to be set by sliders in the control layer, you could put a slider called 'speed' inside the Mercury and Venus layers which simply copied the value from 'Mercury speed' and 'Venus speed' in the control layer. This is a general implementation of that. For a slider called 'speed', it will find a slider in the control layer called 'Foo speed' where 'Foo' is the first word of the current layer’s name. (This allows you to have multiple layers called things like 'Foo green' and 'Foo blue' which share properties, but will only use the first word when looking for the control.) ```javascript thisComp.layer("controls").effect(thisLayer.name.split(" ")[0] + " " + thisProperty.propertyGroup(1).name)("Slider"); ``` ### Dropdown menus Dropdown menu controls return a 1-indexed number representing the selected option. There doesn’t seem to be a way to get the name of that option, which is annoying. So don’t reorder your options after you’ve made expressions for them. And, don’t forget: _1_-indexed, not 0-indexed. ## Layers ### A simple grid of layers Paste this into the position property of many layers, and they will be arranged in a grid based on the x and y spacing and number of columns specified in a sliders in a control layer of your choice. Do not use this in the top layer, as its position is set manually to act as a parent to the rest of the grid. ```javascript // Layer containing slider controls controls_layer = thisComp.layer("controls") // Sliders controlling spacing x_spacing = controls_layer.effect("x spacing")("Slider"); y_spacing = controls_layer.effect("y spacing")("Slider"); // Number of columns is a quick and easy way to control the grid's extent // (Number of rows is implied by the total number of layers) n_col = controls_layer.effect("number of columns")("Slider"); // Topmost layer in the grid top_layer = thisComp.layer("parent layer"); // Get the top left position based on the top layer top_left = top_layer.transform.position; // How far through the grid are we? Count the number of layers before this one layer_index = thisLayer.index - top_layer.index; // Calculate position based on all of the above [ // Loop over x positions with layer index mod number of columns top_left[0] + x_spacing * (layer_index % n_col), // New row every n_col top_left[1] + y_spacing * Math.floor(layer_index/n_col) ]; ``` ### Objects within a shape layer Shape layers can contain multiple objects, like Rectangle 1, Circle 2 etc. Sometimes you might want to address these as though they’re layers, and apply effects based on the properties of adjacent ones, or the top object, or whatever. The syntax for this is somewhat ridiculous. This simple example gets the index of the current object, and then retrieves the opacity of the object below: ```javascript i = thisProperty.propertyGroup(2).propertyIndex; thisLayer("Contents")(i+1).transform.opacity; ``` You can also directly access objects within a shape layer by name, using `content('Name')`; in this case the position of a circle: ```javascript content("Circle 1").content("Path").position; ``` `content("Circle 1").content('Path')` refers to the circle path itself; `content("Circle 1").transform` allows you to access transform controls for that individual shape; and so on. Note that both the path and the transform controls have a `position` property, because shape layers have lots of ways to do the same thing. ## Keyframes ### Finding the previous or next keyframe of a property After Effects doesn’t have a built-in way to select the previous or next keyframe, only the nearest one. These two functions fix that. By default, the expression is applied to the property being manipulated, but you can pass the property you wish to look inside with the `prop` argument. ```javascript function previousKey(prop = thisProperty) { if(time < prop.nearestKey(time).time) { prevIndex = prop.nearestKey(time).index - 1 if(prevIndex <= 0) { return(false); } else { return prop.key(prevIndex); } } else { return prop.nearestKey(time); } } function nextKey(prop = thisProperty) { if(time >= prop.nearestKey(time).time) { nextIndex = prop.nearestKey(time).index + 1 if(nextIndex > prop.numKeys) { return(false); } else { return prop.key(nextIndex); } } else { return prop.nearestKey(time); } } nextKey().index ``` ### Fixing AE’s terrible keyframe interpolation Sometimes (often), After Effects will do very strange things between keyframes with similar values if the preceding or subsequent keyframes involve rapid change of those values. If you just can’t fix it, this function will do it for you in the case where you’d like the keyframe interpolation to be linear, using the previous and next keyframe functions defined above. You could probably extend this to rewrite all interpolation if the type of keyframe is accessible to JavaScript… ```javascript // Get the previous and next keyframes previous_keyframe = previousKey(); next_keyframe = nextKey(); // If they both exist... if(previous_keyframe !== false & next_keyframe !== false) { // Use a simple linear interpolation between them output = linear(time, previous_keyframe.time, next_keyframe.time, previous_keyframe.value, next_keyframe.value); } else { // But, if one is missing, just return the current value output = value; } output; ``` ### Taking a moving average to smooth over janky keyframes Sometimes you’ll generate one keyframe for every frame of the video (eg by 3D camera tracking and the like), but these keyframes can jump occasionally for no good reason. One way to cover this if precision isn’t important is to just smooth over the changes with a moving average: ```javascript // Number of frames (forward and backward) over which to average window_frames = 60; // Loop from -window_frames to +window_frames, summing the values mav = 0; for(i=-window_frames; i<=window_frames; i++) { t = time + i; x = valueAtTime(t); mav += x; } // Divide by the total number of frames averaged over to get an average mav /= window_frames*2; // Use the resulting value mav; ``` When using angles, the moving average approach might not work. eg with orientation, values close to ‘0’ may be 1° or 359°. There’s probably a slightly more general way to write this depending on the place your values are centred on, but here’s a quick kludge for the most common case: ```javascript window_frames = 60; // function to make values near 360 be small negative numbers function rebase(x) { for(j=0; j<3; j++) { if(x[j] > 180) { x[j] = 360-x[j]; } } return(x); } // function to return small negative numbers to be near 360 function unrebase(x) { for(j=0; j<3; j++) { if(x[j] < 0) { x[j] = 360+x[j]; } } return(x); } mav = 0; for(i=-window_frames; i<=window_frames; i++) { t = time + i; x = valueAtTime(t); // Add the value after 'rebasing' mav += rebase(x); } mav /= window_frames*2; // Use the corrected value unrebase(mav); ``` ## Text ### Make text appear character by character ```javascript text.sourceText.substring(0, effect("Slider Control")("Slider")); ``` Simply add a slider control in the text layer, and this allows the text to ‘type’ to appear (or do a bunch of other stuff, obviously). ### A simple clock ```javascript offsetHours = 0; offsetMinutes = 0; offsetSeconds = 0; timeOffset = offsetHours*3600 + offsetMinutes*60 + offsetSeconds; realTime = time + timeOffset ; hh = ("00"+Math.floor(realTime/3600)).substr(-2); mm = ("00"+Math.floor((realTime/60)%60)).substr(-2); ss = ("00"+Math.floor(realTime%60)).substr(-2); mm + ':' + ss; ``` This is a general-purpose script to write a clock that starts at `offsetHours` etc at the start of a composition, and outputs the time to a text layer. The adding zeros at the start and taking a substring thing is a kludgey way to ensure leading zeros. This simple version has no offset and displays minutes and seconds, so it’s just the video playback time. ### Deleting and typing text by keyframes Using the previous and next keyframe functions (defined elsewhere), this function will look ahead to the next keyframe in some text and delete the existing text ahead of it at a rate defined by a slider, and then type the new text after it at a rate defined by a different slider. I realised after writing this that it doesn’t actually need the `prevKey()` and `nextKey()` functions, you could just use `nearKey()` and do different things depending on whether `time - nearKey(time).time` was positive or negative. At least this is clearer! ```javascript function prevKey(prop = thisProperty) { if(time < prop.nearestKey(time).time) { prevIndex = prop.nearestKey(time).index - 1 if(prevIndex <= 0) { return(false); } else { return prop.key(prevIndex); } } else { return prop.nearestKey(time); } } function nextKey(prop = thisProperty) { if(time >= prop.nearestKey(time).time) { nextIndex = prop.nearestKey(time).index + 1 if(nextIndex > prop.numKeys) { return(false); } else { return prop.key(nextIndex); } } else { return prop.nearestKey(time); } } // Get the per-character deleting and typing times from the control layer deleteCharacter = thisComp.layer("controls").effect("delete time")("Slider"); typeCharacter = thisComp.layer("controls").effect("type time")("Slider"); // Get the previous and next text values prevText = prevKey().value; nextText = nextKey().value; // Find out how long it would take to delete and type them, respectively deleteTime = prevText.length * deleteCharacter; typeTime = prevText.length * typeCharacter; // Find out how far away the nearest or next keys are timeSincePrevKey = time - prevKey().time; timeToNextKey = nextKey().time - time; // if(timeToNextKey < deleteTime) { texty = prevText.substr(0,Math.round(timeToNextKey/deleteTime*prevText.length)); } else if (timeSincePrevKey < typeTime) { texty = prevText.substr(0,Math.round(timeSincePrevKey/typeTime*prevText.length)); } else { texty = prevText; } texty; ``` ## Data-driven animation ### Accessing data within a CSV The most general way to do this is using the `.dataValue()` function, which is called in a slightly weird way. You need to have your footage in the composition, but then you don’t call it from its layer, but using the `footage()` function, and then use zero-indexed row and column numbers to access the values, which are accessed backwards, as column, row, because of course they are: ```javascript footage("my-data.csv").dataValue([column,row]) ``` ## Shape layers ### Make a bar grow from the left By default, the anchor point on a rectangle in a shape layer is `[0,0]`, which means, if you increase its size, it will grow from the centre. For a graph, you might want it to instead grow from the left. Putting this expression in the shape’s *Transform > Anchor Point* property will fix this by dynamically moving the anchor as the rectangle expands: ```javascript [ -thisLayer("Contents")(thisProperty.propertyGroup(2).propertyIndex).content(1).size[0]/2, 0 ]; ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully