Centering Sketch using p5.dom

I am attempting to center a sketch in an html page using the dom library. I have followed the reference (https://p5js.org/reference/#/p5.Element/position), as well as instructions on GitHub (https://github.com/processing/p5.js/wiki/Positioning-your-canvas), but have had no luck. When I run my code I receive the error messages

Uncaught TypeError: Cannot read property 'prototype' of undefined
    at p5.dom.js:71
    at p5.dom.js:34
    at p5.dom.js:35

and

Uncaught TypeError: myCanvas.position is not a function
    at setup (paint.html:24)
    at p5.<anonymous> (p5.js:9111)
    at p5.<anonymous> (p5.js:9041)
    at new p5 (p5.js:9323)
    at _globalInit (p5.js:5602)

Here is my code (I've included HTML for convenience).

<!DOCTYPE html>
<html>
    <head>
        <script language="javascript" type="text/javascript" src="p5.dom.js"></script>
        <script src="p5.js"></script>
        <script language="javascript" type="text/javascript" src="p5.sound.js"></script>
        <title>painthead</title>
    </head>
    <body>

      <script>

  var mic;
  var myCanvas;            

  function setup() {
  mic = new p5.AudioIn()
  mic.start();
  myCanvas = createCanvas(1000, 600);    
  myCanvas.position(50, 100); //this breaks the code
  img = loadImage('1.jpg');

}

function draw() {

  background(255);

  if(mouseIsPressed) {
    micLevel = mic.getLevel();
    var c = color('#f99991');
    var v = color('#fdfaee');
    background(v);
    textFont("Helvetica");
    text("do", 500*micLevel+200, 600*micLevel+300);
    fill(c);
  }

  else {
  micLevel = mic.getLevel();  
  image(img, 200*micLevel*50, -50*micLevel*50, img.width/2, img.height/2);
  }
}


        </script>

I realize that myCanvas.position(50, 100) will not center the sketch but I am testing the function to make sure it works.

Answers

  • edited March 2017 Answer ✓

    B/c the other 3rd-party libraries depend on p5.js, we need to load the latter 1st! #-o
    Also consider having your sketch in a separate file. I generally name it: "sketch.js"
    Here's my "index.html" template when I want all those 3 libraries together for 1 "sketch.js": :\">

    <script async src=https://CDN.JSDelivr.net/g/p5.js(p5.min.js+addons/p5.dom.js+addons/p5.sound.js)></script>
    <script defer src=sketch.js></script>
    
  • Perfect! Thanks for the fix. That makes sense.

Sign In or Register to comment.