Adding p5.js sketches to Kirby

Shay Moradi
3 min readJan 2, 2018

--

I love Kirby CMS. It’s very elegant if you’re after a minimal footprint CMS. You buy a license. Download a nice theme, customise it and you’ve got yourself the best, no frills, flat file CMS there is. The back-end is beautiful, beats the bloat of Wordpress.

I recently found myself in the position of wanting to post some of my code experiments in processing / p5.js to my blog posts there. There were no plugins I could find.

I couldn’t just add the P5.js header and script tags to an article template and header and expect any code I entered into the editor to magically work.

Here’s how I did it.

Decide where you want your p5.js code to appear.
For me this was the blog section. I wanted it to be as easy as writing a blog post and adding some p5.js code directly into the editor. Fortunately, Kirby uses Blueprints to say what goes in the text files.

I modified the blueprint to add a new field called p5jscode. It’s important to be consistent with this field name,

Blueprints > Article.yml

In Kirby each page is made up of a Header Snippet, Main Content and Footer.

I decided I was going to create a new header type.
I called this header-p5js.php I made sure at the bottom of this snippet I added

<meta name=”viewport” width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0>
<script src=”../p5js/p5.min.js”></script>
<script src=”../p5js/p5.dom.min.js”></script>
<script src=”../p5js/p5.sound.min.js”></script>

Also don’t forget to copy those files into your root.

new header file in snippets

Now you have to make sure you call this header file in your article.php template.

<?php snippet(‘header-p5js’) ?>

and while you have article.php open you need to make sure you place the P5.js field content somewhere

<div id=”sketch-holder”>
<?= $page->p5jscode()->html() ?>
</div>

Templates > Article.php

That’s it. The only issue with that is your theme itself. If you’ve used the p5.js example embed then it’ll probably clash with your theme and your sketch will appear at the end of your post. That’s why I’ve put it inside a DIV
it an ID of <div id=”sketch-holder”>

When you want to embed your sketch on your site, make sure you amend your setup field of your sketch to have these two lines.

var canvas = createCanvas(500, 400);
canvas.parent(‘sketch-holder’);

This article was super useful to me. https://github.com/processing/p5.js/wiki/Positioning-your-canvas

--

--