user3542502 user3542502 - 1 year ago 105
AngularJS Question

I want to create konvajs stage using angularjs directive can anyone help me

I tried below code in my controller and it's working fine, but I do not have an idea how to convert below code into a directive. I want to create a directive in angularjs and include that into the index.html file.

'use strict';

//prepared stage object
var preparedStage;

//onload function will call first when controller invkoed
function onLoad() {
var width = window.innerWidth;
var height = window.innerHeight;

// first we need Konva core things: stage and layer
preparedStage = new Konva.Stage({
container: 'container',
width: width,
height: height

//stage controller
function StageController($scope) {
//load function
//get prepared stage object.
var stage = preparedStage;
//get layer object
var layer = new Konva.Layer();
//add laeyr onto the stage

// then we are going to draw into special canvas element
var canvas = document.createElement('canvas');
canvas.width = 800;
canvas.height = 400;
// creted canvas we can add to layer as "Konva.Image" element
var image = new Konva.Image({
image: canvas,
x: stage.width() / 4,
y: stage.height() / 4,
stroke: 'green',
shadowBlur: 15
//add image onto the layer
//finally drew the stage.
//angular module
var app = angular.module('app', []),
requires = [
//controller with dependences array.
app.controller('StageController', requires);

Answer Source

Here's something which might help you. Although this example uses KineticJs which is old version of KonvaJs. So just replace Kinetic with Konva and things will work for you.

(function() {
    'use strict';
    .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 konva= {
                    stage: new Konva.Stage({
                        container: id,
                        width: stageWidth,
                        height: stageHeight

                scope.konva= konva;

                $rootScope.$broadcast('KONVA:READY', konva.stage);