我正在尝试使用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)
}
答案 0 :(得分:1)
要在幅度条之间放置空间,可以向每个条的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