Arash Saidi Arash Saidi - 1 year ago 108
HTML Question

Integrating p5js in a Meteor project

I have a little p5js script that I want to incorporate in a Meteor project. I put p5js itself in client/compatibility/p5.min.js and I put my p5js script in client/p5js/sketch1.js.

This is my script:

var sketch1 = function (s) {
s.setup = function () {
s.createCanvas(100, 100);

s.draw = function () {


new p5(sketch1, "sketch1");

It does get injected in the html, but not under the div with id="sketch1". This is the html when I open the console:

<canvas id="defaultCanvas0" class="" width="300" height="300" style="width: 100px; height: 100px;"></canvas>
<div id="sketch1"></div>

Any ideas why this happens, and how I can solve this? The usual behavior is that the canvas is injected inside the div with id="sketch1".

Answer Source

I found a solution to my problem. Very simple solution. In order for p5js to inject itself, the DOM has to be rendered. In my case the DOM is not rendered, hence the canvas is not injected into the div with id "sketch1".

The solution is to use the onRendered method of Meteor:

Template.templateName.onRendered(function() {
    new p5(sketch1, "sketch1");

This ensures the DOM is rendered before the sketch is created, and it will then be injected into the DOM element with the id "sketch1".