The following probably ought not be done, as it seems, at best, poor programming style. Perhaps, even worse, it could break in the future. However, as of this time, it does work without any obvious problem, so here goes, followed after the second example by a question …
The following randomly chooses between two different setup()
functions at runtime, each designating a different canvas size, among other details:
function preload() {
/**** randomly choose a setup function ****/
switch (random([0, 1])) {
case 0:
setup = function () {
createCanvas(377, 233);
background(255, 64, 128);
fill(255, 128);
stroke(0);
noLoop();
};
break;
default:
setup = function () {
createCanvas(233, 144);
background(255, 128, 64);
fill(0, 128);
stroke(255);
noLoop();
};
break;
}
}
function draw() {
rect(5 * width / 16, height / 5, width / 2, height / 3);
triangle(
width / 2,
height / 4,
width / 4,
(height * 3) / 4,
(width * 3) / 4,
(height * 3) / 4
);
}
We have been warned about Things That May Break Your 2.x Sketches. Specifically, it was stated:
Do not use variables in
size()
- This time we really mean it. …
Technically, the above example does not use variables in size()
, but it does defer defining the dimensions of the canvas.
This second example randomly chooses between three different draw()
functions at runtime:
function setup() {
createCanvas(377, 233);
noLoop();
rectMode(CENTER);
background(255, 255, 127);
fill(255, 255, 255, 127);
/**** randomly choose a draw function ****/
switch (random([0, 1, 2])) {
case 0:
draw = function () {
let nudge = width / 12;
rect(width / 2 + nudge, height / 2, width / 2, height / 2);
rect(width / 3 + nudge, height / 3, width / 2, height / 3);
};
break;
case 1:
draw = function () {
let nudge = width / 12;
ellipse(width / 2 + nudge, 3 * height / 5, width / 2, height / 2);
rect(width / 3 + nudge, height / 3, width / 2, height / 3);
};
break;
default:
draw = function () {
let nudge = width / 12;
triangle(
width / 2 + nudge,
height / 4,
width / 4 + nudge,
(height * 3) / 4,
(width * 3) / 4 + nudge,
(height * 3) / 4
);
rect(width / 3 + nudge, height / 3, width / 2, height / 3);
};
}
}
Regarding both of these examples, there are obviously other means of accomplishing the same effects. But, here’s the question … Are there any circumstances at all under which it would be beneficial to choose between alternative definitions of setup()
or draw()
at runtime?