canvas上文字怎么自动大小

阅读 18.2k
5 个回答

我来凑个热闹的。
说一说想法吧。
首先文字的大小是和字体有关的,所以不同的字体,不同类型的字(中文英文数字符号)所占的宽度是不一致的,所以没办法用一个固定的量来计算文字的总宽度,查了下Canvas的API,有一个measureText方法,可以计算字体的宽度。尽管不是很精确但是还是有参考价值的。
我的想法是,可以在每次渲染文字前,想measureText一下文字的总宽度,然后,如果超出了给定区域,就进行缩放,然后居中。
缩放比就用字体的总宽度除以给定区域的宽度就好了。
试了一下,代码如下:

 var canvas = document.getElementById("myCanvas");
    var canvasWidth = canvas.width;
    var context = canvas.getContext("2d");

    var x = 0;
    var y = 400;
    context.font = "500px 微软雅黑";

    var textWidth = context.measureText("Hello World").width;
    if(textWidth>canvasWidth) {
        var scaled = canvasWidth/textWidth;
        context.scale(scaled,scaled);
    }
    //x,y用于居中, canvas第一次使用,搞不明白x,y用的是什么单位,所以写死在这里了。
    context.fillText("Hello World!", x, y);

结果

clipboard.png

另外我这里没有考虑高度方向的溢出。可能有bug吧

页面的使用不是告诉你怎么使用吗?
你可以在font的配置项中设置,然后再生成啊
你计算好图片大小和font-size之间的关系,在需要holder的时候
再通过window.placeholder.getData(opts); 生成base64格式的图片数据赋值给img的src

//option config
var opts = {
    size: '512x256', //image size, default: '128x128'
    bgcolor: '#ccc', //background-color, default: random color
    color: '#969696', //text color, default: random color
    text: 'Hello World, 你好', //text on image, default: size
    font: {
        style:'oblique', //font-style, can be: normal / italic / oblique, default: 'oblique'
        weight: 'bold', //font-weight, can be: normal / bold / bolder / lighter / Number, default: 'bold'
        size:'40', //font-size: Number, default: 30
        family: 'consolas' //font-family, default: 'consolas'
  },

}
//API method
//1. get the image base64 
window.placeholder.getData(opts); 
//2. get the image canvas element
window.placeholder.getCanvas(opts); //get the image canvas element