Skip to content

Instantly share code, notes, and snippets.

@wilt00
Created August 28, 2022 23:26
Show Gist options
  • Save wilt00/b41580d2ee85a409ecfaf71491f473fd to your computer and use it in GitHub Desktop.
Save wilt00/b41580d2ee85a409ecfaf71491f473fd to your computer and use it in GitHub Desktop.
A simple one-octave piano in <1kB of HTML/JS
<canvas id="p">
<script>
n = document.getElementById('p')
c = n.getContext('2d')
for(i=0;i<8;i++){c.strokeRect(i*37+2,1,37,148)}
bx=[24,67,134,176,218,286]
db=x=>c.fillRect(x,0,22,100)
bx.map(db)
ac=0
g=0
o=0
h=Array.from({length:14},(_,i)=>261.63*Math.pow(2,1/12)**i)
hb=[1,3,6,8,10,13]
hw=[0,2,4,5,7,9,11,12]
mm=e=>{
bi=bx.findIndex(b=>e.x>=b&&e.x<=b+22)
if(bi>=0&&e.y<=100) {
o.frequency.value=h[hb[bi]]
}else{
o.frequency.value=h[hw[0|e.x/37]]
}
}
n.addEventListener('mousemove',mm)
n.addEventListener('mousedown',e=>{
if(!ac){
ac=new window.AudioContext()
g=ac.createGain()
g.connect(ac.destination)
o=ac.createOscillator()
o.connect(g)
o.start()
}
mm(e)
g.gain.setValueAtTime(1,ac.currentTime)
})
n.addEventListener('mouseup',e=>g.gain.setValueAtTime(0,ac.currentTime))
console.log(n)
console.log(c)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment