casper123
casper123

Reputation: 1766

KineticJS toImage Width and Height issue

Im running into this strange problem..! I've a kineticJS text element and I'm converting it into image.. Here is the Code

var simpleText = new Kinetic.Text({
    x: 50,
    y: 50,
    text: $("#text").val(),
    fontSize: $("#fontSize").val(),
    fontFamily: $("#fontName").val(),
    fill: $("#fontColor").val(),
});

var twidth = simpleText.getWidth();
var theight = simpleText.getHeight();

simpleText.toImage({
    width:twidth,
    height:theight,
    callback: function(img){
        var textImg = new Kinetic.Image({
            image: img,
            x: 0,
            y: 0,
            width: twidth,
            height: theight,
            name: 'image',
            stroke: 'red',
            strokeWidth: 2,
            strokeEnabled: false
        });

        addElement(textImg, textImg.getWidth(), textImg.getHeight());
    }
});

So the problem exist here..!

var twidth = simpleText.getWidth();
var theight = simpleText.getHeight();

If I just put the width and height in numeric form, everything works fine and text is converted, something like this

var twidth = 500;
var theight = 100;

But if I use simpleText.getWidth() and simpleText.getHeight(), nothing happens, the image is created but it doesn't have that TEXT. As I saw in documentation, width and height are optional params for toImage(), so I removed now, but now its show this error..

Uncaught TypeError: Cannot read property 'bufferCanvas' of undefined kinetic.js:28 Kinetic.Node.toDataURL kinetic.js:28 Kinetic.Node.toImage kinetic.js:28 add_text canvas.js:83 (anonymous function) canvas.js:352 f.event.dispatch jquery.min.js:3 h.handle.i

any idea whats wrong with my code?

Upvotes: 1

Views: 890

Answers (1)

lavrton
lavrton

Reputation: 20308

I am not shure is it bug or feature. But problem is: picture are taken from rectangle with this coordinates: {x:0 y:0}; width and height - what you insert as toImage params. (twidth, theight)

But text has coords {x : 50, y : 50}. So it is outside of "picture" rectagle above. As you say if yor increase width and height:

var twidth = 500;
var theight = 100;

Everything is fine and you will see text, but image will be big with empty space.

So... just insert "x" and "y" params to toImage function:

simpleText.toImage({
    width:twidth,
    height:theight,
    x : 50,
    y : 50,
    callback: function(img){
        $('body').append($(img));
    }
});

example: http://jsfiddle.net/lavrton/hgax2/

Upvotes: 2

Related Questions