An Ember Canvas Component

May 11, 2014

By Jamison Dance

How to render data to a canvas element with Ember.js

You want to render some data to a <canvas> tag. You are also using Ember. Boy do I have a blog post for you.

Ember is optimized for the common case of rendering data to the DOM. If you want to do something different, like render to <canvas>, Ember provides a few hooks to do so.

First, let's make a basic app with a component. We grab the ember dependencies and create a template for our component.

Notice the name is "compontents/canvas-thing". Ember components must have a dash in their name, and the template name must start with component/. See the components guide for more specifics on this.

The default HTML tag for a component is a <div>. Since we want to use a <canvas> tag, we need to create a custom JavaScript class to override it. This will come in handy later when we need to draw in it as well.

We create a component subclass, override the html tag, and set some default attributes to control the element size. Again, pretty basic stuff.

Draw me like one of your french components

An empty canvas element is pretty lame. We still haven't drawn anything. Ember provides the didInsertElement hook, which will be called once our canvas is in the DOM. Let's implement it to draw some stuff!

You should see a black box on your screen. Take a moment now to stand up and gaze triumphantly into the distance with your clenched fist raised over your head, because you are awesome.

However, this isn't actually rendering any of your data. Worse, it won't update when your data changes! Let's fix that.

Updating when data changes

To update the component when data changes, we can just create a draw method that draws the data, and observes the data. Looky here:

This got a little more complex, but the concepts are simple. We create a draw method like we said. It draws the data as text, and then some sweet stars for bling. The rest is cleanup and helper functions around this.

The important thing to note is the .observes('data') at the end of the draw method. This calls draw whenever the data changes. We'll add a little input helper to the application template to show this off.

We grab the text from the input and send it in to the component. Watch how it updates, and also sparkles. Pretty neat!

Behold the final result:

Ember Starter Kit

If you make it draw cooler things than stars, like dinosaurs or laser beams or laser dinosaurs, please let me know @jergason.

Jamison Dance enjoys kittens, making computers smarter and the magic of children's laughter. He tweets at @jergason and GitHubs as jergason. He also podcasts on JavaScript Jabber and Soft Skills Engineering.