做了一个开源项目 https://github.com/hustcc/placeholder.js
项目官网地址:http://placeholder.cn/
可以在每次渲染文字前,想measureText一下文字的总宽度,然后,如果超出了给定区域,就进行scale缩放,然后居中。
做了一个开源项目 https://github.com/hustcc/placeholder.js
项目官网地址:http://placeholder.cn/
可以在每次渲染文字前,想measureText一下文字的总宽度,然后,如果超出了给定区域,就进行scale缩放,然后居中。
感谢大家,刚刚用scale已经解决了自动宽度的问题,欢迎大家去测试:https://github.com/hustcc/placeholder.js
官网预览地址 :http://placeholder.cn/
页面的使用不是告诉你怎么使用吗?
你可以在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
计算文字长宽你需要这个方法:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText
注意 ie9 才支持
另外一个问题,你的 canvas 没有根据屏幕像素比缩放,所以在 Retina 屏幕上是有些模糊的,
https://github.com/component/autoscale-canvas/blob/master/index.js
这儿有一种缩放的实现
5 回答2.2k 阅读
4 回答1.5k 阅读
我来凑个热闹的。
说一说想法吧。
首先文字的大小是和字体有关的,所以不同的字体,不同类型的字(中文英文数字符号)所占的宽度是不一致的,所以没办法用一个固定的量来计算文字的总宽度,查了下Canvas的API,有一个measureText方法,可以计算字体的宽度。尽管不是很精确但是还是有参考价值的。
我的想法是,可以在每次渲染文字前,想measureText一下文字的总宽度,然后,如果超出了给定区域,就进行缩放,然后居中。
缩放比就用字体的总宽度除以给定区域的宽度就好了。
试了一下,代码如下:
结果
另外我这里没有考虑高度方向的溢出。可能有bug吧