基于egg.js生成圣诞帽
2024-11-17 11:40:26
egg,canvas生成圣诞帽
2400
首先我们需要一个egg.js框架,前提是安装了node
$ mkdir egg-example && cd egg-example $ npm init egg --type=simple $ npm i
如果有cnpm 更佳
$ mkdir egg-example && cd egg-example $ cnpm init egg --type=simple $ cnpm i
安装一个canvas模块
cnpm i -S canvas 启动项目,查看http://127.0.0.1:7001/是否可以正常访问 npm run dev
然后找一个半透明的圣诞帽子放在根目录,命名为logo.png 把app\controller\home.js路径下的文件全部替换
'use strict'; const Controller = require('egg').Controller; const { createCanvas, loadImage, Image } = require('canvas'); class HomeController extends Controller { async index() { const { ctx } = this; //获取参数,最好改为post let { base64, width = 128, height = 128 } = ctx.query; //提示 if (!base64) { ctx.body = { success:false, data:null, meg:`base64缺一不可!` }; return; } let res = await getData({base64,width, height}); if (res.success) { ctx.body = res.data } else { ctx.body = res; } } } function getData({ base64, width, height }) { return new Promise((resolve, reject) => { const canvas = createCanvas(width, height) const context = canvas.getContext('2d') const img = new Image(); img.onload = () => context.drawImage(img, 0, 0, width, height); img.onerror = err => { reject({ success: false, data: err, msg:'头像加载出错' }) } img.src = base64; loadImage('./logo.png').then(image => { context.drawImage(image, 0, 0, 90, 90); canvas.toDataURL('image/png', (err, png) => { if (err) { reject({ success: false, data: err, msg:'圣诞帽没有带上' }); } else { resolve({ success: true, data: png, msg:'圣诞帽成功' }) } }) }) }) } module.exports = HomeController;
现在把base64的头像作为url参数就可以得到戴帽子的base64了
http://127.0.0.1:7001/?base64=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
今天,你学废了么