xxxxxxxxxx
let osc, playing, frequen, amps;
let ripples = [];
function setup() {
let cnv = createCanvas(400, 400);
cnv.mousePressed(playOscillator);
osc = new p5.Oscillator();
}
function draw() {
background(220)
frequen = constrain(map(mouseX, 0, width, 100, 500), 100, 500);
amps = constrain(map(mouseY, height, 0, 0, 1), 0, 1);
if (playing) {
// smooth the transitions by 0.1 seconds
osc.freq(frequen, 0.1);
osc.amp(amps, 0.1);
osc.setType('sine');
}
for (let i = ripples.length - 1; i >= 0; i--) {
ripples[i].update();
ripples[i].display();
if (ripples[i].isFinished()) {
ripples.splice(i, 1);
}
}
}
function playOscillator() {
// starting an oscillator on a user gesture will enable audio
// in browsers that have a strict autoplay policy.
// See also: userStartAudio();
osc.start();
playing = true;
}
function mouseReleased() {
// ramp amplitude to 0 over 0.5 seconds
osc.amp(0, 0.5);
playing = false;
}
function mousePressed() {
ripples.push(new Ripple(mouseX, mouseY));
}
class Ripple {
constructor(x, y) {
this.x = x;
this.y = y;
this.radius = 0;
this.maxRadius = 100;
this.speed = 4;
this.opacity = 255;
}
update() {
this.radius += this.speed;
this.opacity -= 5;
}
display() {
noFill();
stroke(0, this.opacity);
strokeWeight(2);
ellipse(this.x, this.y, this.radius * 2);
let colorR = map(this.radius, 0, this.maxRadius, 255, 100);
let colorG = map(this.radius, 0, this.maxRadius, 100, 255);
fill(colorR, colorG, 100, this.opacity);
noStroke();
ellipse(this.x, this.y, this.radius * 2);
}
isFinished() {
return this.opacity <= 0;
}
}