DEV Community

Cover image for HTML canvas, web components and pianos.
Hyena
Hyena

Posted on • Updated on

HTML canvas, web components and pianos.

If you've ever thought about starting to code a music web application, chances are you've needed a piano keyboard in your HTML.

Notice how little code is needed to add a keyboard to an HTML page:

<html>
  <body>
    <piano-keyboard height="100" width="800" octaves="5"></piano-keyboard>
  </body>
  <script src="https://cdn.jsdelivr.net/gh/rafapaezbas/piano-keyboard/piano-keyboard.js"></script>
</html>
Enter fullscreen mode Exit fullscreen mode

<piano-keyboard> ? That tag doesn't exist! No problem, web components to the rescue!

If you don't know what a web component is, let me explain quickly: a web component is a fully customized html element, but it's just as easy to use as any standard web element. You can see a good tutorial following this link.

Or maybe you are interested in seeing the full code of the component.

A calendar, a knob or a writing keyboard are good candidates to create a web component due to their reusability. Create the component and reuse or share the code. Also don't be afraid that the component's logic will interfere with your application's logic, this logic is fully encapsulated! A web component can only communicate with its parent by emitting events.

A simple example:

// hello-world-component.js

window.customElements.define('hello-world', class HelloWorld extends HTMLElement {
  builder () {
    super()
    this.root = this.attachShadow({ mode: 'open' })
  }

  async connectedCallback() {
      this.dispatchEvent(new CustomEvent('hello-world-event, { detail: { message: 'hello word!' }, bubbles: true, composed: true }))
  }
}
Enter fullscreen mode Exit fullscreen mode

To include the component in your HTML page just add the script:

<html>
  <body>
    <hello-world></hello-world>
  </body>
  <script src="hello-world-component.js"></script>
  <script>
    document.querySelector('hello-world').addEventListener('hello-world-event', (e) => {
      console.log(e.detail.message))
    })
  </script>
</html>
Enter fullscreen mode Exit fullscreen mode

It's that easy to create your own web component!

Of course, the combination of web components and HTML canvas offers endless possibilities. It's easy to imagine a collection of components that makes building and maintaining web applications truly modular.

Top comments (0)