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
the components guide for
more specifics on this.
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
that draws the data, and observes the data. Looky here:
This got a little more complex, but the concepts are simple. We create a
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
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:
If you make it draw cooler things than stars, like dinosaurs or laser beams or laser dinosaurs, please let me know @jamison_dance.