canvas图片制作

canvas安装有时会出现无法更新状态 可以设置npm配置canvas镜像

npm install canvas --canvas_binary_host_mirror=https://npm.taobao.org/mirrors/node-canvas-prebuilt/ 

生成图片:
const fs = require('fs');

const path = require('path');

const { loadImage, createCanvas} = require('canvas');

let generateClassImage =async (name,  icon , back , filePath)=> {

    let image =await loadImage(back); //加载背景图

    let {width, height} = image; //获取背景图宽高

    let cv = createCanvas(width, height); //创建cv

    let ctx = cv.getContext('2d');

    ctx.drawImage(image, 0, 0); //将背景图写入画布

    ctx.font ='30px Impact';

    ctx.textAlign ='center';

    ctx.fillText(name, 160, 120); //编辑名字

    ctx.stroke();

    let iconImage =await loadImage(icon );  //加载icon图

    ctx.drawImage(iconImage, 38, 732, 236, 236); //将icon图 写入画布

    let buf = cv.toDataURL();

    let base64Data = buf.replace(/^data:image\/\w+;base64,/, ""); //生成图片格式

    let dataBuffer = Buffer.from(base64Data, 'base64'); 

    fs.writeFileSync(filePath, dataBuffer); //保存图片

};

图片翻转 读取成base64数据

const fs =require("fs");

const util =require("util");

const imageData =await util.promisify(fs.readFileSync(fileUrl));/

const imageBase64 = imageData.toString("base64");

const imagePrefix ="data:image/png;base64,";

console.log(imagePrefix + imageBase64);

你可能感兴趣的:(canvas图片制作)