简体   繁体   English

JS文本到图像改变字体大小

[英]JS Text to image changing the size of font

http://jsfiddle.net/amaan/WxmQR/1 http://jsfiddle.net/amaan/WxmQR/1

HTML: HTML:

<canvas id='textCanvas' height=20></canvas>
<img id='image'>
<br>
<textarea id='text'></textarea>

CSS: CSS:

canvas{
    border: 1px black solid;
}
#textCanvas{
    display: none;
}

JS: JS:

var tCtx = document.getElementById('textCanvas').getContext('2d'),
    imageElem = document.getElementById('image');

document.getElementById('text').addEventListener('keyup', function (){
    tCtx.canvas.width = tCtx.measureText(this.value).width;
    tCtx.fillText(this.value, 0, 10);
    imageElem.src = tCtx.canvas.toDataURL();
    console.log(imageElem.src);
}, false);

This Code is what I want but I want to be able to make the font size bigger, have a fixed width and height for the image and make the text to over flow to the next line.这段代码是我想要的,但我希望能够使字体变大,图像具有固定的宽度和高度,并使文本溢出到下一行。 Thanks in advance.提前致谢。

Shortest way:最短路径:

document.getElementById("myP").style.fontSize = "xx-large";

How ever, this will add the style attribute to the text area element, which is not recommended.但是,这将向文本区域元素添加style属性,这是不推荐的。 instead, create a class with the desired font size and call it like this:相反,创建一个具有所需字体大小的类并像这样调用它:

document.getElementById("myP").className = "MyClass"; 

As the best practice states, all designs should be inside a style sheet (css file) and not defined in the html element itself.正如最佳实践所述,所有设计都应该在样式表(css 文件)中,而不是在 html 元素本身中定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM