Embedding p5.js in WordPress

// Sept 2018 //

How to embed a P5JS sketch onto a wordpress page using just an iframe.

1. You need to create an html file that looks like this. Change the src addresses to point to your p5.js and p5.dom.js files and your own foo.js sketch on your server. Upload this html file onto your server in your script area along with the p5 files.

<html>
<head>
<meta charset="UTF-8">
<script src=".../p5.js" type="text/javascript"></script>
<script src=".../p5.dom.js" type="text/javascript"></script>
<script src=".../foo.js" type="text/javascript"></script>
</head>

<body>
<div id="holder"></div>
</body>

</html>

2. next you need to write your p5.js sketch. The html will display this sketch using an iframe. This simple code example would just draws a white ellipse on a red background. Notice the key line is canvas.parent(‘holder’) which is named the same as in the html file. This sketch also needs to be uploaded to the server.

function setup() { 
  var canvas = createCanvas(300, 200); 
  canvas.parent('holder');
} 

function draw() { 
  background(255,0,0);
  fill(255,255,255);
  ellipse(150,100,50,50);
}

3. The sketch above will be 300×200 pixels, so we need an iframe just a bit bigger than this. In WordPress create a new post go to text mode and insert the following code anywhere on the page, changing the src to point to your own html file.

<iframe src="...foo.html" width="320px" height="220px"></iframe>

And here is an example of the process in action with a more interactive p5.js sketch.