Hannes Tiltmann
Hannes Tiltmann

Reputation: 2356

Creating a canvas in JavaScript based on variables (with p5.js)

I want to draw a simple canvas based on variables.

It works like this:

function setup() {
   createCanvas(600, 600);
   background(50);
}

Why does that not work? (a small canvas, definitely not 600x600 is displayed):

var height = 600;
var width = 600;

function setup() {
    createCanvas(height, width);
    background(50)
}

I appreciate any help!

Upvotes: 0

Views: 1148

Answers (2)

Dreamer
Dreamer

Reputation: 171

From what i have learnt for p5.js Library, I do believe that the width and height variable are dedicated to the canvas created by the createCanvas() and are systems variable, and renaming those variable would most likely solve the problem.

Upvotes: 1

Mare_413
Mare_413

Reputation: 417

It doesnt work because height and width are built-in p5 variable names. Try renaming them to something else.

var a = 600;
var b = 600;

function setup() {
    createCanvas(a, b);
    background(50)
}

If you are looking to make the canvas the size of the window, you should use windowWidth and windowHeight.

function setup() {
  createCanvas(windowWidth, windowHeight);
}

To resize the canvas after setup you should do something like this:

var c;

function setup() {
  c = createCanvas(windowWidth-20, windowHeight-20);
}

function draw() {
  background(30);
}

function mousePressed() {
    c.size(windowWidth-20, windowHeight-20);
    console.log(width + " " + height);
}

Upvotes: 2

Related Questions