UNPKG

2.71 kBMarkdownView Raw
1## P5JS
2
3Smartdown integrates the wonderful [P5.js](https://p5js.org/) Javascript library, which provides a way for authors to embed *sketches* within their Smartdown documents.
4
5
6### P5JS Ellipse Example
7
8
9```p5js/playable
10p5.setup = function() {
11};
12
13p5.draw = function() {
14 p5.ellipse(50, 50, 80, 80);
15};
16```
17
18
19### P5JS Sound Oscillator Frequency Example
20
21Here is the [P5JS Sound Oscillator Frequency Example](https://p5js.org/examples/examples/Sound_Oscillator_Frequency.php).
22
23```p5js/playable
24var osc, fft;
25
26p5.setup = function () {
27 p5.createCanvas(420, 256);
28
29 osc = new p5.TriOsc(); // set frequency and type
30 osc.amp(.5);
31 osc.owner = p5;
32
33 fft = new p5.FFT();
34 fft.owner = p5;
35 osc.start();
36};
37
38p5.draw = function () {
39 p5.background(255);
40
41 var waveform = fft.waveform(); // analyze the waveform
42 p5.beginShape();
43 p5.strokeWeight(5);
44 for (var i = 0; i < waveform.length; i++) {
45 var x = p5.map(i, 0, waveform.length, 0, p5.width);
46 var y = p5.map(waveform[i], -1, 1, p5.height, 0);
47 p5.vertex(x, y);
48 }
49 p5.endShape();
50
51 // change oscillator frequency based on mouseX
52 var freq = p5.map(p5.mouseX, 0, p5.width, 40, 880);
53 osc.freq(freq);
54 var amp = p5.map(p5.mouseY, 0, p5.height, 1, .01);
55 osc.amp(amp);
56};
57```
58
59
60### P5JS Playback Rate Example
61
62Here is the [P5JS Playback Rate Example](https://p5js.org/examples/examples/Sound_Playback_Rate.php). Load a SoundFile and map its playback rate to mouseY, volume to mouseX.
63
64
65```p5js/playable
66// A sound file object
67var song;
68
69p5.preload = function () {
70 // Load a sound file
71 song = p5.loadSound(p5.exampleSound);
72 song.owner = p5;
73};
74
75p5.windowResized = function() {
76 p5.resizeCanvas(p5.windowWidth - 70, 100);
77};
78
79p5.setup = function () {
80 p5.createCanvas(100, 100);
81 p5.windowResized();
82 // Loop the sound forever
83 // (well, at least until stop() is called)
84 song.loop();
85};
86
87p5.draw = function () {
88 p5.background(200);
89
90 // Set the volume to a range between 0 and 1.0
91 var volume = p5.map(p5.mouseX, 0, p5.width, 0, 1);
92 volume = p5.constrain(volume, 0, 1);
93 song.amp(volume);
94
95 // Set the rate to a range between 0.1 and 4
96 // Changing the rate alters the pitch
97 var speed = p5.map(p5.mouseY, 0.1, p5.height, 0, 2);
98 speed = p5.constrain(speed, 0.01, 4);
99 song.rate(speed);
100
101 // Draw some circles to show what is going on
102 p5.stroke(0);
103 p5.fill(51, 100);
104 p5.ellipse(p5.mouseX, 100, 48, 48);
105 p5.stroke(0);
106 p5.fill(51, 100);
107 p5.ellipse(100, p5.mouseY, 48, 48);
108};
109```
110
111### More P5JS Examples
112
113[P5JS Mobius](:@Mobius)
114[P5JS Conic Sections](:@Conic)
115[P5JS Game](:@Games)
116[P5JS Tree](:@Tree)
117[P5JS VectorField](:@VectorField)
118[P5JS VectorTree](:@VectorTree)
119
120---
121
122[Back to Home](:@Home)
123