javascript 如何基于文本和 CSS 生成图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17618574/
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
How can I generate an image based on text and CSS?
提问by Lucas T.
I'm developing a web app. It generates signatures for a game, with information from its API.
我正在开发一个网络应用程序。它使用来自其 API 的信息为游戏生成签名。
I'll need to store the images with a script that gathers the information and turns it into an image.
我需要使用脚本来存储图像,该脚本收集信息并将其转换为图像。
Do you know a way to turn text + CSS into an image?
你知道一种将文本 + CSS 转换成图像的方法吗?
回答by nycynik
Yes this can be done, what you want to do is draw the text on a canvas, and then save the canvas. you do not need to have the canvas show, you can hide it like any other html element, just add it, draw the text on it, and save it.
是的,这可以做到,您要做的是在画布上绘制文本,然后保存画布。您不需要显示画布,您可以像任何其他 html 元素一样隐藏它,只需添加它,在其上绘制文本并保存即可。
Here is a link on a library that saves: https://github.com/hongru/canvas2image
这是一个保存库的链接:https: //github.com/hongru/canvas2image
Some sample code drawing text on canvas:
在画布上绘制文本的一些示例代码:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="30px Arial";
ctx.fillText("Your Text",10,50);
// save img
Canvas2Image.saveAsImage(c, 200, 100, 'png');
</script>