Where to add custom theme function that generates HTML?
Your nearly there...

If your going to do this on the theme layer then create the custom function and call it in a process function assigning to a variable that can be passed to the template.

Thats typically the "Drupal way".

template.php

function THEME_customFunction() {
   // blah blah...
}


template.php

function THEME_preprocess_page(&amp;$vars) {
   // blah blah...

   $vars['animation'] = THEME_customFunction();

}


page.tpl.php

&lt;?php if ($animation): ?&gt;
&lt;?php print $animation; ?&gt;
&lt;?php endif; ?&gt;