Javascript 使用javascript将文本转换为图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12328714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:43:56  来源:igfitidea点击:

Convert Text to Image using javascript

javascripthtmltext

提问by Shab

Is there any way I can convert the input text into an image. What I am exactly trying to do is type some text into a textbox and display it on div. When I click on a button the text copied to div should be changed to an image. Does anyone know anything about this? Thanks in advance!

有什么办法可以将输入文本转换为图像。我真正想做的是在文本框中键入一些文本并将其显示在 div 上。当我单击按钮时,复制到 div 的文本应更改为图像。有人对这个有了解吗?提前致谢!

回答by Some Guy

You can do this using a hidden canvas element and converting that to an image using toDataURL. Your code would look something like this:

您可以使用隐藏的画布元素执行此操作,并使用 将其转换为图像toDataURL。您的代码如下所示:

var tCtx = document.getElementById('textCanvas').getContext('2d'), //Hidden canvas
    imageElem = document.getElementById('image'); //Image element
// Text input element
document.getElementById('textInput').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);
?

Demo

演示

回答by Frank van Puffelen

The canvas approach suggested by Amaan is definitely today's approach to generating images client-side.

Amaan 建议的画布方法绝对是当今生成客户端图像的方法。

In the past, the most common solution was to use a library like Cufon. From the Cufon wiki page on its usagecomes this snippet:

过去,最常见的解决方案是使用像Cufon这样的库。从Cufon wiki 页面上可以看到这个片段:

<script type="text/javascript">
    Cufon.replace('h1'); // Works without a selector engine
    Cufon.replace('#sub1'); // Requires a selector engine for IE 6-7, see above
</script>

Cufon generates the client-side version of the font up-front. This means it just adds static files on your web server, instead of generating the images on the web server (like with ImageMagick).

Cufon 预先生成字体的客户端版本。这意味着它只是在您的 Web 服务器上添加静态文件,而不是在 Web 服务器上生成图像(如 ImageMagick)。

回答by K-man

You need to use ImageMagick on your server side. Depending on what kind of framework you use, you may have to write some nice shell scripts.

您需要在服务器端使用 ImageMagick。根据您使用的框架类型,您可能需要编写一些不错的 shell 脚本。

OR

或者

You can check this out:

你可以看看这个:

http://www.blitline.com/docs/functions

http://www.blitline.com/docs/functions