Animate drawbox width and height in FFmpeg

Drawing animated bounding boxes in FFmpeg allows you to highlight text or objects dynamically. This article explains how to use the drawbox and drawtext filters in FFmpeg to create a box that expands or contracts over time by utilizing mathematical expressions in the width and height parameters.

The Core Concept

To animate the width and height of a bounding box, you must leverage the t (time in seconds) variable within the drawbox filter’s expression evaluator. By combining t with mathematical functions like min(), max(), and conditional operators, you can control the growth speed and define the final dimensions of the box.

The FFmpeg Command

The following command draws an expanding red background box that stops growing after two seconds, followed by a text overlay.

ffmpeg -i input.mp4 -vf "drawbox=x=100:y=100:w='min(400\, t*200)':h='min(80\, t*40)':color=red@0.5:t=fill, drawtext=text='Dynamic Box':x=120:y=125:fontsize=24:fontcolor=white" -c:a copy output.mp4

How the Animation Works

  1. drawbox Parameters:
    • x=100 & y=100: Sets the top-left starting coordinate of the box.
    • w='min(400\, t*200)': Animates the width. The expression evaluates to t * 200 pixels per second. The min(400, ...) function ensures that once the width reaches 400 pixels (at the 2-second mark), it stops growing. (Note: The comma inside the filter expression must be escaped with a backslash \, to prevent FFmpeg from interpreting it as a filter parameter separator).
    • h='min(80\, t*40)': Animates the height. It grows at a rate of 40 pixels per second and caps at a maximum height of 80 pixels.
    • color=red@0.5: Sets the box color to red with a 50% opacity.
    • t=fill: Fills the inside of the bounding box.
  2. drawtext Parameters:
    • x=120 & y=125: Positions the text slightly inside the animated box boundaries.
    • fontsize=24 & fontcolor=white: Styles the text so it is clearly readable over the animated background.

Adding a Delayed Start

If you want the animation to start after a specific timestamp (e.g., at 3 seconds), you can use conditional statements inside the expressions:

w='if(gte(t\, 3)\, min(400\, (t-3)*200)\, 0)'

In this formula: * gte(t\, 3) checks if the current video time is greater than or equal to 3 seconds. * If true, it starts growing the width from 0 at a rate of 200 pixels per second. * If false, the width remains 0 (invisible).