この記事はtomowarkar ひとりAdvent Calendar 2019の17日目の記事です。
はじめに
HTMLとJavaScriptを書いてサクッとピアノを実装したってだけのお話。
デモサイト
コード
piano/
├── index.html
├── script.js
├── sounds
│ ├── do.mp3
│ ├── fa.mp3
│ ├── mi.mp3
│ ├── ra.mp3
│ ├── re.mp3
│ ├── si.mp3
│ └── so.mp3
└── style.css
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0" />
<title></title>
<link rel="stylesheet" href="style.css" type="text/css">
<script defer src="script.js"></script>
</head>
<body>
<div class="piano">
<div data-sound="do" class="key white"></div>
<div class="black"></div>
<div data-sound="re" class="key white"></div>
<div class="black"></div>
<div data-sound="mi" class="key white"></div>
<div data-sound="fa" class="key white"></div>
<div class="black"></div>
<div data-sound="so" class="key white"></div>
<div class="black"></div>
<div data-sound="ra" class="key white"></div>
<div class="black"></div>
<div data-sound="si" class="key white"></div>
</div>
<audio id="do" src="sounds/do.mp3"></audio>
<audio id="re" src="sounds/re.mp3"></audio>
<audio id="mi" src="sounds/mi.mp3"></audio>
<audio id="fa" src="sounds/fa.mp3"></audio>
<audio id="so" src="sounds/so.mp3"></audio>
<audio id="ra" src="sounds/ra.mp3"></audio>
<audio id="si" src="sounds/si.mp3"></audio>
</body>
</html>
style.css
*{
box-sizing: border-box;
}
body{
background-color: green;
margin: 0;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.piano{
display: flex;
}
.white{
width:80px;
height: 320px;
background-color: white;
border: 1px solid gray;
}
.black{
width:48px;
height: 192px;
background-color: black;
margin-left: -24px;
margin-right: -24px;
z-index: 2;
}
script.js
const keys = document.querySelectorAll('.key')
keys.forEach(key=>{
key.addEventListener('click', ()=>playPiano(key))
})
function playPiano(key) {
const audio = document.getElementById(key.dataset.sound)
audio.currentTime = 0
audio.play()
}
おわりに
案外簡単に実装できますねー
以上明日も頑張ります!!
tomowarkar ひとりAdvent Calendar Advent Calendar 2019