使用P5.js,我试图创建一个在mp3播放时绘制的视觉效果。随着歌曲的进行,画布上画了一个矩形来说明它的振幅。我遇到了一个问题,每个矩形的间距。有了我写出的代码,它们就会被画在彼此的旁边,但我理想的情况下是介于1或2px之间。
这是我现在所拥有的:

这就是我想要的:

如有任何建议,我们将不胜感激!下面是我的代码:
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)
}发布于 2019-05-02 08:15:15
要在振幅条之间放置间距,可以向每个条的x位置添加一个偏移量。要使条形的高度随振幅而变化,可以将每个矩形的高度设置为映射的振幅,然后通过计算其y位置使其居中。
使用偏移量,您的draw函数将如下所示:
function draw(){
background(245)
stroke(0, 109, 203)
//populate volHistory
if(song.isPlaying()){
var vol = amp.getLevel()
volHistory.push(vol)
}
//iterate through volHistory and draw
fill(0, 109, 203)
var barWidth = 2;
var offsetWidth = 5;
var offset = 5;
for(var i = 0; i < volHistory.length; i++){
var barHeight = map(volHistory[i], 0, 1, 1, height)
rect(i + offset, (height/2.0) - (barHeight/2.0), barWidth, barHeight);
offset += offsetWidth;
}
//moves wavelength 1 index at a time and account for bar width and offset width
if(volHistory.length * (offsetWidth + barWidth) > width - 10){
volHistory.splice(0, 1)
}
//draw vertical line
stroke(250, 30, 100)
line(volHistory.length + offset, 0, volHistory.length + offset, height)
}请注意,在此绘图中,createCanvas已移至setup
https://stackoverflow.com/questions/55943459
复制相似问题