思路:
文字转svg,svg转png
需要引入两个依赖:
npm i text-to-svg 文字转svg
npm i svg2png svg转png图片
文字转svg:
const express = require('express');
const app = express();
const TextToSVG = require('text-to-svg');
const textToSVG = TextToSVG.loadSync('fonts/文泉驿微米黑.ttf');
app.all("*",function(req,res,next){
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin","*");
//允许的header类型
res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Accept,Content-type");
res.header("Access-Control-Allow-Credentials",true);
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("Content-Type","application/json;charset=utf-8")
if (req.method.toLowerCase() == 'options')
res.sendStatus(200); //让options尝试请求快速结束
else
next();
});
const attributes = {fill: 'red', stroke: 'black'};
const options = {
x: 0,
y: 0,
fontSize: 72,
anchor: 'top',
attributes: attributes,
};
app.get('/test',(req,res)=>{
const svg = textToSVG.getSVG('hello', options);
res.send(svg);
})
app.listen(8000);
在前台页面当中使用ajax访问请求
<script>
//1.创建ajax对象
var xhr = new XMLHttpRequest();
//2.告诉ajax请求地址以及请求方式
xhr.open('get','http://localhost:8000/test');
//3.发送请求
xhr.send();
//4.获取服务器端给与客户端的响应数据
xhr.onload = function(){
console.log(xhr.responseText);
//xhr.responseText返回值是String
document.body.innerHTML=xhr.responseText;
}
在前台页面加一个表单:
<input type="text" id="ipt">
<button type="button" id="btn">提交</button>
<script>
var btn = document.querySelector('#btn');
var ipt = document.querySelector('#ipt');
btn.addEventListener('click',function(){
//1.创建ajax对象
var xhr = new XMLHttpRequest();
//2.告诉ajax请求地址以及请求方式
console.log(ipt.value);
xhr.open('get','http://localhost:8000/test?test='+ipt.value);
//3.发送请求
xhr.send();
//4.获取服务器端给与客户端的响应数据
xhr.onload = function(){
console.log(xhr.responseText);
//xhr.responseText返回值是String
document.body.innerHTML=xhr.responseText;
}
})
</script>
后台接收数据:
app.get('/test',(req,res)=>{
console.log(req.query.text);
const svg = textToSVG.getSVG(req.query.text, options);
res.send(svg);
})
app.get('/test',(req,res)=>{
const svg = textToSVG.getSVG(req.query.text, options);
res.send(svg);
})
把svg类型的图片转为png类型的图片:
安装依赖:
npm i svg-to-img
转png用法:
const svg = textToSVG.getSVG('hello', options);
(async () => {
const image = await svgToImg.from(svg).toPng({
path: "./text.png"
});
console.log(image);
})();
转jpeg:
const svgToImg = require("svg-to-img");
(async () => {
await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toJpeg({
path: "./example.jpeg"
});
})();
webp:
const svgToImg = require("svg-to-img");
(async () => {
const image = await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toWebp({
width: 300
});
console.log(image);
})();
base64-encoded png:
const svgToImg = require("svg-to-img");
(async () => {
const image = await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toPng({
encoding: "base64"
});
console.log(image);
})();