123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              #drum-machine
img#pic(src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Drum_Kit_3.svg/2000px-Drum_Kit_3.svg.png" alt="DRUM MACHINE!")
            
          
!
            
              @import url('https://fonts.googleapis.com/css?family=Heebo|Orbitron|Righteous');

// $stripe1: #0FFF95;
// $stripe2: #06BA63;
// $border1: #103900;
$stripe1: #D4AA7D;
$stripe2: #EFD09E;
$stripe3: #665843;
$stripe4: #565133;
$border1: #66513C;
$border2: #3F3225;
$light: #E2D686;

body {
  font-family: "Heebo", cursive, sans-serif;
  background: #FFEEEE;
  background: -webkit-linear-gradient(to right, #DDEFBB, #FFEEEE); 
  background: linear-gradient(to right, #DDEFBB, #FFEEEE);
  display: flex;
  justify-content: center;
  align-items: center;
  @media (max-width: 665px) {
    display: block;
  }
}

button:hover {
  cursor: pointer;
}

input {
  width: 40px;
}

#display {
  border: 15px ridge $border2;
  border-radius: 10px;
  display: block;
    background: repeating-linear-gradient(
    45deg,
    $stripe3,
    $stripe3 5px,
    $stripe4 5px,
    $stripe4 10px
  );
}

.flexCenter {
  display: flex;
  justify-content: center;
}

.controls {
  @extend .flexCenter;
  align-items: "center";
  width: 100%;
  flex-wrap: wrap;
  & label {
    margin-top: 20px;
  }
}

.bpmInput {
  height: 20px;
  margin-top: 15px;
  background: rgba(255,249,196,1);
  font-family: 'Orbitron', sans-serif;
  border: 5px $border1 inset;
}

.controlBtn {
  margin: 10px;
  -moz-box-shadow:inset 0px 1px 0px 0px #a6827e;
	-webkit-box-shadow:inset 0px 1px 0px 0px #a6827e;
	box-shadow:inset 0px 1px 0px 0px #a6827e;
	background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #d9be36), color-stop(1, #c29232));
	background:-moz-linear-gradient(top, #d9be36 5%, #c29232 100%);
	background:-webkit-linear-gradient(top, #d9be36 5%, #c29232 100%);
	background:-o-linear-gradient(top, #d9be36 5%, #c29232 100%);
	background:-ms-linear-gradient(top, #d9be36 5%, #c29232 100%);
	background:linear-gradient(to bottom, #d9be36 5%, #c29232 100%);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#d9be36', endColorstr='#c29232',GradientType=0);
	background-color:#d9be36;
	-moz-border-radius:3px;
	-webkit-border-radius:3px;
	border-radius:3px;
	border:1px solid #54381e;
	display:inline-block;
	cursor:pointer;
	color:#ffffff;
	font-family: 'Orbitron', sans-serif;
	font-size:13px;
	padding:6px 24px;
	text-decoration:none;
	text-shadow:0px 1px 0px #4d3534;
  &:hover {
    background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #c29232), color-stop(1, #d9be36));
    background:-moz-linear-gradient(top, #c29232 5%, #d9be36 100%);
    background:-webkit-linear-gradient(top, #c29232 5%, #d9be36 100%);
    background:-o-linear-gradient(top, #c29232 5%, #d9be36 100%);
    background:-ms-linear-gradient(top, #c29232 5%, #d9be36 100%);
    background:linear-gradient(to bottom, #c29232 5%, #d9be36 100%);
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#c29232', endColorstr='#d9be36',GradientType=0);
    background-color:#c29232;
  }
  &:active {
    position:relative;
	  top:1px;
  }
}

.drumMachineContainer {
  display: block;
  width: 530px;
  margin: 10px;
  padding: 15px;
  background: repeating-linear-gradient(
    45deg,
    $stripe2,
    $stripe2 10px,
    $stripe1 10px,
    $stripe1 20px
  );
  @media (max-width: 635px) {
    overflow-x: scroll;
  } 
  border-radius: 5px;
  border: 10px $border1 inset;
}

.drumPads {
  display: flex;
  flex-wrap: wrap;
  width: 80px;
}

.drum-pad {
  width: 80px;
  margin: 10px;
  -moz-box-shadow:inset 0px 1px 0px 0px #a6827e;
	-webkit-box-shadow:inset 0px 1px 0px 0px #a6827e;
	box-shadow:inset 0px 1px 0px 0px #a6827e;
	background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #c78e56), color-stop(1, #613b13));
	background:-moz-linear-gradient(top, #c78e56 5%, #613b13 100%);
	background:-webkit-linear-gradient(top, #c78e56 5%, #613b13 100%);
	background:-o-linear-gradient(top, #c78e56 5%, #613b13 100%);
	background:-ms-linear-gradient(top, #c78e56 5%, #613b13 100%);
	background:linear-gradient(to bottom, #c78e56 5%, #613b13 100%);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#c78e56', endColorstr='#613b13',GradientType=0);
	background-color:#c78e56;
	-moz-border-radius:3px;
	-webkit-border-radius:3px;
	border-radius:3px;
	border:1px solid #54381e;
	display:inline-block;
	cursor:pointer;
	color:#ffffff;
	font-family:Arial;
	font-size:13px;
	padding:6px 24px;
	text-decoration:none;
	text-shadow:0px 1px 0px #4d3534;
  &:hover {
    background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #613b13), color-stop(1, #c78e56));
    background:-moz-linear-gradient(top, #613b13 5%, #c78e56 100%);
    background:-webkit-linear-gradient(top, #613b13 5%, #c78e56 100%);
    background:-o-linear-gradient(top, #613b13 5%, #c78e56 100%);
    background:-ms-linear-gradient(top, #613b13 5%, #c78e56 100%);
    background:linear-gradient(to bottom, #613b13 5%, #c78e56 100%);
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#613b13', endColorstr='#c78e56',GradientType=0);
    background-color:#613b13;
  }
  &:active {
    @extend .btnActive;
  }
}

.btnActive {
  position:relative;
  color: gold;
  top:1px;
}

.drumName {
  @extend .flexCenter;
  width: 100px;
  align-items: center;
}

.noteRow {
  display: flex;
  flex-wrap: no-wrap;
}

.completeRow {
  display: flex;
}

.toggleButton {
  width: 20px;
  border: 3px ridge #555555;
}

.light {
  background: black;
  border: 3px ridge #555555;
  border-radius: 50%;
  width: 14px;
  height: 10px;
}

#pic {
  position: fixed;
  width: 200px;
  height: 200px;
  z-index: -1;
  top: calc(50vh - 100px);
  left: calc(50vw - 100px);
}
            
          
!
            
              const _keyChars = "Q, W, E, A, S, D, Z, X, C".match(/[A-Z]/g);
const url = "https://s3.eu-west-2.amazonaws.com/drumkit-fcc/";
const audioFiles = "crash ride tomHigh tomLow openHat closedHat clap snare kick".split(" ");
const originalState = {};
const aud = {};

// Howler Audio & Create Original State

for (const _key of _keyChars) {
  originalState[_key] = "0".repeat(16);
  const keyIndex = _keyChars.indexOf(_key);
  aud[_key] = new Howl({
    src: url+audioFiles[keyIndex]+".mp3"
  });
}

// Redux

const noteReducer = (state = originalState, action) => {
  if (_keyChars.indexOf(action.type) > -1 && action.type !== "reset") {
    let newObj = Object.assign(state);
    let spl = newObj[action.type].split("");
    spl[action.timing] = spl[action.timing] === "0" ? "1" : "0";
    let newRow = spl.join("");
    newObj[action.type] = newRow;
    return newObj;
  } else if (action.type === "reset") {
    let blankSlate = {};
    for (const _key of _keyChars) {
      blankSlate[_key] = "0".repeat(16);
    }
    return blankSlate;         
  } else if (action.type === "demo") {
    const demoComposition = {
      A: "0000000000001000",
      C: "1000000010000000",
      D: "0111011101110101",
      E: "0000100000000000",
      Q: "0000000010000000",
      S: "0000000000000010",
      W: "1000000000000000",
      X: "0000100000001000",
      Z: "0000000000000010"
    }
    return demoComposition;
  } else {
    return state;
  }
}

const store = Redux.createStore(noteReducer);

const toggleNote = (_noteKey, _timing) => store.dispatch({
  type: _noteKey,
  timing: _timing
});

// React

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      playing: false,
      currentPosition: 0,
      bpm: 120
    }
    this.handleChange = this.handleChange.bind(this);
    this.playComposition = this.playComposition.bind(this);
    this.play = this.play.bind(this);
    this.stop = this.stop.bind(this);
    this.pause = this.pause.bind(this);
    this.reset = this.reset.bind(this);
  }
  handleChange(e) {
    let val = e.target.value;
    if (val > 0 && val < 1000) this.setState({bpm: val});
  }
  playComposition() {
    if (!this.state.playing) this.setState({playing: true}, () => this.play());
  }
  play() {
    let composition = store.getState(); // May not want to call this every note
    for (let i = 0; i < _keyChars.length; i++) {
      if (composition[_keyChars[i]][this.state.currentPosition] === "1") {
        aud[_keyChars[i]].play();
      }
    }
    if (this.state.playing) {
      let nextPosition = this.state.currentPosition === 15 ? 0 : this.state.currentPosition + 1;
      this.setState({ currentPosition: nextPosition });
      setTimeout(() => {
        if (this.state.playing) this.play();
      }, 15000 / this.state.bpm);
    }
  }
  pause() {
    for (let i = 0; i < _keyChars.length; i++) {
      aud[_keyChars[i]].stop();
    }
    this.setState({
      playing: false
    });
  }
  stop() {
    for (let i = 0; i < _keyChars.length; i++) {
      aud[_keyChars[i]].stop();
    }
    this.setState({
      playing: false,
      currentPosition: 0
    });
  }
  reset() {
    if (confirm("Are you sure you want to reset everything?")) {
      store.dispatch({type: "reset"});
      this.forceUpdate();
    }
  }
  render() {
    return (
      <div id="display">
        <div className="controls">
          <button className="controlBtn" onClick={this.playComposition}><i class="material-icons">play_arrow</i></button>
          <button className="controlBtn" onClick={this.stop}><i class="material-icons">stop</i></button>
          <button className="controlBtn" onClick={this.pause}><i class="material-icons">pause</i></button>
          <label>BPM:&nbsp; </label>
          <input className="bpmInput" type="number" value={this.state.bpm} onChange={this.handleChange}></input>
          <button className="controlBtn" onClick={this.reset}>Reset</button>
        </div>
        <div className="flexCenter">
          <div className="drumMachineContainer">
            <Drums playing={this.state.playing} position={this.state.currentPosition} keyChars={_keyChars} /> 
          </div>
        </div>
      </div>
    );
  }
}

class Drums extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const drumArr = [];
    const kc = this.props.keyChars;
    const drumNames = audioFiles.map(a => {
      if (/[A-Z]/.test(a)) {
        let arr = a.split("");
        let regMatch = a.match(/[A-Z]/);
        arr.splice(arr.indexOf(regMatch[0]), 0, " ");
        a = arr.join("");
      } 
      a = a.replace(a[0], a[0].toUpperCase());
      return a;
    });
    for (let i = 0; i < kc.length; i++) {
      drumArr.push(
        <div className="completeRow">
          <label id={"name-"+kc[i]} className="drumName">{drumNames[i]}</label>
          <button onClick={() => aud[kc[i].toString()].play()} className="drum-pad" id={"drum-"+kc[i]} key={"drum-"+kc[i]}>{kc[i]}</button>
          <NoteRow key={"row-"+kc[i]} note={kc[i]}/>
        </div>
      );
    }
    // Lights to show current position
    const posLights = <PositionLights playing={this.props.playing} position={this.props.position} />
    drumArr.unshift(posLights);
    drumArr.push(posLights);
    return(
      <div className="drumPads">{drumArr}</div>
    );
  }
}
  
class NoteRow extends React.Component {
  constructor(props) {
    super(props);
    this.rowButtons = this.rowButtons.bind(this);
    this.toggle = this.toggle.bind(this);
  }
  toggle(n, ind) {
    toggleNote(n, ind);
    aud[n].play();
    this.forceUpdate();
  }
  btnActive(active) {
    if (active) {
      return {
        backgroundColor: "#E2D686"
      }
    } else {
      return {
        backgroundColor: "#404444"
      }
    }
  }
  rowButtons() {
    let arr = [];
    for (let i = 0; i < 16; i++) {
      arr.push(
        <button 
          style={this.btnActive(store.getState()[this.props.note][i] === "1")} 
          className="toggleButton" 
          onClick={() => this.toggle(this.props.note, i)}>
        </button>
      );
    }
    return arr;
  }
  render() {
    return (
      <div className="noteRow">
        {this.rowButtons()}
      </div>
    );
  }
}

class PositionLights extends React.Component {
  constructor(props) {
    super(props);
    this.onOff = this.onOff.bind(this);
  }
  onOff(index) {
    if (this.props.playing && this.props.position === index) {
      return { backgroundColor: "#AFC97E"}; 
    } else {
      return { backgroundColor: "black"}; 
    }
  };
  render() {
    const gap = { width: 200 };
    const lights = [];
    for (let i = 0; i < 16; i++) {
      lights.push(<div key={"light-"+i} style={this.onOff(i)} className="light" />)
    }
    return (
      <div className="completeRow"><div style={gap}></div>{lights}</div>
    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("drum-machine"));

// Keypress Event Listeners

window.addEventListener("keypress", hitKey, false);

function hitKey(e) {
  //const codesForChars = [113, 119, 101, 97, 115, 100, 122, 120, 99];
  const codesForChars = _keyChars.map(k => k.toLowerCase().charCodeAt(0));
  if (codesForChars.indexOf(e.keyCode) > -1) {
    let userKey = String.fromCharCode(e.keyCode).toUpperCase();
    aud[userKey].play();
    let drum = document.getElementById('drum-'+userKey);
    let name = document.getElementById('name-'+userKey);
    drum.classList.add("btnActive");
    name.classList.add("btnActive");
    setTimeout(() => {
      drum.classList.remove("btnActive");
      name.classList.remove("btnActive");
    }, 200);
  }
}
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console