-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathchooser.js
More file actions
93 lines (75 loc) · 2.45 KB
/
chooser.js
File metadata and controls
93 lines (75 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import canvasSketch from 'canvas-sketch';
import { sketches } from './sketches';
const settings = {
dimensions: [ 1024, 1024 ],
animate: true
};
document.addEventListener('DOMContentLoaded', () => {
let managerP = null;
addSketchMenu(sketches, (sketch, div) => {
if (sketch === undefined) {
console.log("Undefined sketch");
return;
}
console.log(`Executing sketch ${sketch.name}`);
if (sketch.createPane !== undefined) {
sketch.createPane(div);
}
// Stop the old sketch - we don't bother garbage collecting these but just
// want to ensure our sketch render function is no longer being called.
if (managerP !== null) {
managerP.then((manager) => manager.stop());
}
managerP = canvasSketch(sketch.sketch, settings);
});
});
function addSketchMenu(sketches, onSketch) {
// Retain the viewed sketch across browser refreshes
let currentSketch = parseInt(localStorage.getItem('current-sketch'));
if (isNaN(currentSketch) || currentSketch >= sketches.length) {
currentSketch = 0;
localStorage.setItem('current-sketch', currentSketch);
}
const div = document.createElement('div');
div.style = `width: 100%;
position: absolute;
top: 1em;
left: 1em;
text-align: center;
`;
const select = document.createElement('select');
select.style = 'font-size: 2em;';
div.appendChild(select);
const disabledOption = makeOption("", "Choose a Sketch");
disabledOption.select = true;
disabledOption.disabled = true;
select.add(disabledOption);
for (let i = 0; i < sketches.length; i++) {
select.add(makeOption(i, sketches[i].name));
}
select.addEventListener('change', (e) => {
changeCurrentSketch();
});
const pane = document.createElement('div');
pane.style = 'width: 400px; margin: 1em auto;';
div.appendChild(pane);
document.body.appendChild(div);
onSketch(sketches[currentSketch], pane);
// Wipe out any old sketch, and create a new one.
function changeCurrentSketch() {
pane.innerHTML = null;
let canvas = document.querySelector('canvas');
if (canvas !== null) {
canvas.remove();
}
localStorage.setItem('current-sketch', select.value);
let sketch = sketches[select.value];
onSketch(sketch, pane);
}
}
function makeOption(value, name) {
const opt = document.createElement('option');
opt.value = value;
opt.textContent = name;
return opt;
}