Using P5.js, I'm trying to create a visual that gets drawn as an mp3 plays. As the song progresses, a rectangle is drawn on the canvas to illustrate its amplitude. I'm having a problem with spacing each rectangle. With the code I've written out, they get drawn right next to each other, but I ideally I would like 1 or 2px in between.
Here is what I have now:
This is what I'd like:
Any suggestions would be greatly appreciated! Here is my code:
var song
var button
var amp
var volHistory = []
function preload(){
song = loadSound("next-to-me.mp3")
}
function setup(){
createButtons()
amp = new p5.Amplitude()
}
function togglePlay(){
if(!song.isPlaying()){
song.play()
} else {
song.pause()
}
}
//draw is constantly being run
function draw(){
//styling
createCanvas(400, 150)
background(245)
stroke(0, 109, 203)
//populate volHistory
if(song.isPlaying()){
var vol = amp.getLevel()
volHistory.push(vol)
}
//iterate through volHistory and draw
beginShape()
for(var i = 0; i < volHistory.length; i++){
var y = map(volHistory[i], 0, 1, height/2, true)
fill(0, 109, 203)
rect(i, y, 2, y, 25) //(x, y, w, h, radius)
}
endShape()
//moves wavelength 1 index at a time
if(volHistory.length > width - 10){
volHistory.splice(0, 1)
}
//draw vertical line
stroke(250, 30, 100)
line(volHistory.length, 0, volHistory.length, height)
}
function loaded(){
createButtons()
}
function createButtons(){
button = createButton("<img style='width: 50px' src='http://www.stickpng.com/assets/images/580b57fcd9996e24bc43c4f9.png'/>")
button.mousePressed(togglePlay)
button.position(162, 50)
button.style("background-color", color(0,0,0,0))
button.style("border", 0)
}