How to find start and end points of filltext in canvas

Muhammad Zeeshan Source

Hey there how am i going to find the start and end point of a canvas

i have created a letter like this on a canvas

var centerx = (c.width - cx.measureText(letter).width) / 2;
        var centery = c.height / 2;
        console.log("Bilawal");
        console.log(cx.measureText(letter));
        var lines = letter.split('\n');
        var lineheight = 20;
        //for (var i = 0; i<lines.length; i++)
        //cx.fillText(lines[i], centerx, centery + (i*lineheight) );

        console.log("X "+centerx+" Y "+centery);
        cx.fillText(letter, centerx, centery);

now i dont know how to find the start X,Y and end X,Y

javascripthtmlhtml5canvas

Answers

answered 1 month ago Any Moose #1

You asked for a code sample. Below I have included the same math. Hope this helps.

var centerx = (c.width - cx.measureText(letter).width) / 2;
        var centery = c.height / 2;
        console.log("Bilawal");
        console.log(cx.measureText(letter));
        var lines = letter.split('\n');
        var lineheight = 20;
        //for (var i = 0; i<lines.length; i++)
        //cx.fillText(lines[i], centerx, centery + (i*lineheight) );

        console.log("X "+centerx+" Y "+centery);
        cx.fillText(letter, centerx, centery);

        startx = centerx;
        starty = centery - 10;
        endx = (c.width / 2) + (cx.measureText(letter).width / 2); 
        endy = centery + 10;

Start and end for each letter as you asked. Once it runs you can access the array of COORDS "startsEnds". If the space between the letters is to large drop the spacer value.

function COORD(sx,sy,ex,ey) {
    this.startX = sx;
    this.startY = sy;
    this.endX = ex;
    this.endY = ey;
}

var startsEnds = [];
var spacer = 1;
var centerx = (c.width - cx.measureText(letter).width) / 2;
        var centery = c.height / 2;
        console.log("Bilawal");
        console.log(cx.measureText(letter));
        console.log("X "+centerx+" Y "+centery);

        var lines = letter.split('\n');
        var lineheight = 20;
        //for (var i = 0; i<lines.length; i++)
        //cx.fillText(lines[i], centerx, centery + (i*lineheight) );
        var lett = letter.split("");

        var newCenterX = centerx;
        var newCenterY = centery;

        for (var i = 0; i < lett.length; i++){

            console.log("X "+newCenterX+" Y "+newCenterY );


            var startEnd = new COORD(newCenterX,newCenterY - 10,(c.width / 2) + (cx.measureText(lett[i]).width / 2), newCenterY + 10);
            startsEnds.push(startEnd);

            newCenterX = newCenterX + cx.measureText(lett[i]) + spacer;

        }
        cx.fillText(letter, centerx, centery);

comments powered by Disqus