Letter spacing in canvas element

前端 未结 10 2360
攒了一身酷
攒了一身酷 2020-12-24 06:46

The question says it all pretty much. I\'ve been searching around and starting to worry that it\'s impossible.

I\'ve got this canvas element that I\'m drawing text t

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 07:07

    I don't know about other people but I have adjusted line spacing by increasing the y value on the text that I am writing. I'm actually splitting a string by spaces and kicking each word down a line inside a loop. The numbers i use are based on the default font. If you use a different font that these numbers may need to be adjusted.

    // object holding x and y coordinates
    var vectors = {'x':{1:100, 2:200}, 'y':{1:0, 2:100}
    // replace the first letter of a word
    var newtext = YOURSTRING.replace(/^\b[a-z]/g, function(oldtext) {
        // return it uppercase
        return oldtext.toUpperCase(); 
    });
    // split string by spaces
    newtext = newtext.split(/\s+/);
    
    // line height
    var spacing = 10 ;
    // initial adjustment to position
    var spaceToAdd = 5;
    // for each word in the string draw it based on the coordinates + spacing
    for (var c = 0; c < newtext.length; c++) {
        ctx.fillText(newtext[c], vectors.x[i], vectors.y[i] - spaceToAdd);
        // increment the spacing 
        spaceToAdd += spacing;
    }               
    

提交回复
热议问题