AngularJS + KineticJS = Stage Directive

In the last days I came across an interesting canvas library called Kinetic.js, which called my attention by its easy API. Even though the library provides some complex functionality, like drag and drop, it still feels a pleasure to work with it.
Let me show you how to integrate that with angularjs!
What we need to create is a simple directive called Stage that will
setup a new Kinetic.Stage for us.

You can find the source code for the directive below. It is also available on Github.

(function() {
    'use strict';
    angular.module('kinetic')
    .directive('stage', ['$rootScope',
    function stageDirective ($rootScope) {
        return {
            restrict: 'EA',
            scope: {
                stageWidth: '=',
                stageHeight: '='
            },
            link: function linkFn (scope, elem, attrs) {
                var id = attrs["id"];
                if (!id) {
                    id = Math.random().toString(36).substring(8);
                    elem.attr('id', id);
                }
                var stageWidth = scope.stageWidth || 800;
                var stageHeight = scope.stageHeight || 600;

                var kinetic = {
                    stage: new Kinetic.Stage({
                        container: id,
                        width: stageWidth,
                        height: stageHeight
                    })
                };

                scope.kinetic = kinetic;

                $rootScope.$broadcast('KINETIC:READY', kinetic.stage);
            }
        };
    }]);
})();

Have fun!

Ps.: this post has been in limbo for some time. I’m glad it finally got out!

About Jonas Hartmann

A flying mind. I develop software that gives wings to human imagination.
This entry was posted in AngularJS, Directives, JavaScript, Technologien, Technology, Web, Web development and tagged , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s