Balls

I wanted to add JavaScript to a WordPress post, in order to animate on a canvas element.

Canvas

I added the canvas element in the Code Editor, giving it the unique id myCanvas. The width and height of the element are measured in pixels.

JavaScript

The JavaScript did not need to export any identifiers, and so could be put within a self-invoking anonymous function ((function() {...})();).

Each ball is a value (an object) in array balls. The function ballsMove is called every 10 milliseconds, through the function setInterval. Each ball is moved, in turn. If it intersects a wall (isWall()), or another ball (isBall()), it bounces back and its velocity is affected.

I placed the JavaScript file (named post808.js, after the post id) in a js folder of the theme.

PHP

The theme is a child theme. I used the Child Theme Configurator plugin to add code to its functions.php file. The code adds an action to the wp_head hook. The action uses the is_single() function, which tests whether the query is for an existing single post.

The defer attribute of the script element is necessary to ensure that the page has been parsed before the script searches for the element with id myCanvas.