Best method of scaling text to fill an HTML5 canvas

馋奶兔 提交于 2019-12-13 14:09:46

问题


I need to 'scale' text to fill an antire HTML5 canvas. It appears that the scale() method does not affect text. I've seen approximation methods with iterative loops on the measureText() method but this doesn't get me exactly what I need. Ideally I'd like to fill both horizontally and vertically without conserving the aspect ratio. Would SVG possibly be able to help with this?


回答1:


My bad - Scale DOES apply to text. I've come up with a solution:

context.font = "20px 'Segoe UI'";
var metrics = context.measureText("Testing!");
var textWidth = metrics.width;

var scalex = (canvas.width / textWidth);
var scaley = (canvas.height / 23);

var ypos = (canvas.height / (scaley * 1.25));

context.scale(scalex, scaley);
context.fillText("Testing!", 0, ypos);



回答2:


Scale does affect text. Try this:

var can = document.getElementById('test');
var ctx = can.getContext('2d');

ctx.fillText("test", 10, 10); // not scaled text


ctx.scale(3,3);
ctx.fillText("test", 10, 10); // scaled text

See it in action here: http://jsfiddle.net/3zeBk/8/



来源:https://stackoverflow.com/questions/4114052/best-method-of-scaling-text-to-fill-an-html5-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!