Getting started, throwing errors on copied code

I've copied the following code directly from the p5 github page.

    var canvas;

    function setup() {
      // We are still calling createCanvas like in the past, but now 
      // we are storing the result as a variable. This way we can 
      // call methods of the element, to set the position for instance.
      canvas = createCanvas(600, 400);

      // Here we call methods of each element to set the position 
      // and id, try changing these values.
      // Use the inspector to look at the HTML generated from this 
      // code when you load the sketch in your browser.
      canvas.position(300, 50);
      canvas.class("lemon");
    }

    function draw() {
      // These commands are applied to the graphics canvas as normal.
      background(220, 180, 200);
      ellipse(width/2, height/2, 100, 100);
      ellipse(width/4, height/2, 50, 50);
    }

I get an error on the canvas.position(300,50) line, "undefined is not a function."

If I comment out this line, the code works just fine, although of course the canvas is positioned on the top left of the page.

My HTML, which was also copied directly from the github exampel, for ref:

<html>
  <head>
    <script language="javascript" src="../p5.min.js"></script>
    <!-- uncomment lines below to include extra p5 libraries -->
    <!--<script language="javascript" src="../addons/p5.dom.js"></script>-->
    <!--<script language="javascript" src="../addons/p5.sound.js"></script>-->
    <script language="javascript" src="sketch.js"></script>
    <!-- this line removes any default padding and style. you might only need one of these values set. -->
    <style> body {padding: 0; margin: 0;} </style>
  </head>

  <body>
  </body>

</html>

Answers

  • Found the bug! Identifier canvas is a p5.js' internal tag or something: @-)

    <canvas id=​"defaultCanvas" class=​" p5_hidden lemon" style=​"width:​ 600px;​ height:​ 400px;​ position:​ absolute;​ left:​ 300px;​ top:​ 50px;​" width=​"600" height=​"400">​

  • edited December 2014

    hi @nicerhugs, the .position() and .class() methods are not part of the core p5.js library, they are part of the addon p5.dom.js library. if you working from the downloaded empty example, you should already have this file in your folder, you just need to uncomment this line (meaning remove the symbols at the end):

Sign In or Register to comment.