We are using Lauren McCarthy’s p5.js-embedder, a plugin which embeds an interactive p5.js sketch into a WordPress blog. Here is an example:
function setup() {
createCanvas(640,160);
}
function draw() {
background(255,200,200);
line (0,0, mouseX, mouseY);
line (width,0, mouseX, mouseY);
line (0,height, mouseX, mouseY);
line (width,height, mouseX, mouseY);
fill (255);
ellipse(mouseX, mouseY, 30,30);
noFill();
rect (0,0, width-1, height-1);
}
Instructions for embedding:
0. Create your sketch using p5.js.
1. Upload the sketch.js file (or whatever you’ve named it — it’s much better if it’s named something like julie-landscape.js) to the WordPress Media Library. For the present time, the plugin only permits you to upload a single .js file.
2. While editing post, choose ‘Add Media’ and choose the uploaded JavaScript file; it will add a link in your post.
3. Switch over to the “Text” editing mode in the WordPress editor. This takes you out of the “Visual” (WYSIWYG) mode, and into a pseudo-HTML editing mode. You can do this with the button in the upper right corner, which looks like this:
4. Add class='p5-embed'
to the link to specify it should be parsed as a p5 sketch.
5. If you would like to specify the height and width of the frame of your sketch (which you probably do!) use the data-width
and data-height
tags (you can specify one or both of these). Your embed code may look something like the following (note that I have broken this up onto several lines to make it more readable, and this also illustrates that the attributes href
, class
, data-width
, and data-height
can appear in any order between <a
and >
, and finally, that you can use single- or double-quotes around p5-embed
and other values):
1 2 3 |
<a href="http://my-wordpress-site.com/uploads/my-sketch.js" data-width='600' data-height='400' class='p5-embed'>my-sketch.js</a> |
6. You can also change the code font size with the tag data-fontsize='9'.
Important Restrictions and Workarounds
p5-embed
is not perfect and has some serious defects, but you can easily work around them:
-
- Width limitation: WordPress will clip your canvas to a width of 600, so
data-width
should be 600 or less. - Some operators, in particular
<
, can fool WordPress into thinking you are embedding HTML, so put spaces around operators — this is the style we recommend anyway. Example: do not writehead <body
in your code (those who know HTML will see why). Instead, writebody < head
(with spaces around<
). - The
&
symbol in code comments is also known to create problems, even with spaces. Do not use the&
character in any comments. - To include external files (for example, an image via loadImage command) you will need to upload the files individually to WordPress and use the full blog URL or the upload in the JS code.
- Width limitation: WordPress will clip your canvas to a width of 600, so