tags:

views:

505

answers:

3

I am trying to add text on an image using the <canvas> element. First the image is drawn and on the image the text is drawn. So far so good.

But where I am facing a problem is that if the text is too long, it gets cut off in the start and end by the canvas. I don't plan to resize the canvas, but I was wondering how to wrap the long text into multiple lines so that all of it gets displayed. Can anyone point me at the right direction?

+1  A: 

look at https://developer.mozilla.org/en/Drawing_text_using_a_canvas#measureText%28%29

If you can see the selected text, and see its wider than your canvas, you can remove words, until the text is short enough. With the removed words, you can start at the second line and do the same.

Of course, this will not be very efficient, so you can improve it by not removing one word, but multiple words if you see the text is much wider than the canvas width.

I did not research, but maybe their are even javascript libraries that do this for you

Nathan
A: 

context.measureText(text).width is what you're looking for...

ItzWarty
+1  A: 

Warning : i modified this function, because it was bugged.

A possible method (not completely tested, but as for now it worked perfectly)

    /**
     * Divide an entire phrase in an array of phrases, all with the max pixel length given.
     * The words are initially separated by the space char.
     * @param phrase
     * @param length
     * @return
     */
function getLines(ctx,phrase,maxPxLength,textStyle) {
    var wa=phrase.split(" ");
    var phraseArray=new Array();
    var lastPhrase="";
    ctx.font = textStyle;
    var l=maxPxLength;
    var measure=0;
    for (var i=0;i<wa.length;i++) {
        var w=wa[i];
        measure=ctx.measureText(lastPhrase+w).width;
        if (measure<l) {
            lastPhrase+=(" "+w);
        }else {
            phraseArray.push(lastPhrase);
            lastPhrase=w;
        }
        if (i==wa.length-1) {
            phraseArray.push(lastPhrase);
            break;
        }
    }
    return phraseArray;
}
mizar