本代码片段使用插件《qs-canvas》,支持 Node、web、uni-app 的canvas绘图工具。
效果图
安装npm包
npm install qs-canvas -S
代码片段
// index.vue
// useCanvas.js
/**
* qs-canvas 绘制海报
* @version 1.0.0
* @param {Object} options - 海报参数
* @param {Object} vm - 自定义组件实例
*/
import QSCanvas from 'qs-canvas';
import { getPosterData } from './poster';
export default async function useCanvas(options, vm) {
const width = options.width;
const qsc = new QSCanvas(
{
canvasId: options.canvasId,
width: options.width,
height: options.height,
setCanvasWH: (canvas) => {
options.height = canvas.height;
},
},
vm,
);
let drawer = getPosterData(options);
// 绘制背景图
const background = await qsc.drawImg({
type: 'image',
val: drawer.background,
x: 0,
y: 0,
width,
mode: 'widthFix',
zIndex: 0,
});
await qsc.updateCanvasWH({
width: background.width,
height: background.bottom,
});
let list = drawer.list;
for (let i = 0; i < list.length; i++) {
let item = list[i];
// 绘制文字
if (item.type === 'text') {
await qsc.drawText(item);
}
// 绘制图片
if (item.type === 'image') {
if (item.d) {
qsc.setCircle({
x: item.x,
y: item.y,
d: item.d,
clip: true,
});
}
if (item.r) {
qsc.setRect({
x: item.x,
y: item.y,
height: item.height,
width: item.width,
r: item.r,
clip: true,
});
}
await qsc.drawImg(item);
qsc.restore();
}
// 绘制二维码
if (item.type === 'qrcode') {
await qsc.drawQrCode(item);
}
}
await qsc.draw();
// 延迟执行, 防止不稳定
setTimeout(async () => {
options.src = await qsc.toImage();
}, 100);
return options;
}
// poster/index.js
const invite = (options) => {
const width = options.width;
// const userInfo = sheep.$store('user').userInfo;
const userInfo = {
avatar: 'https://fakeimg.pl/60x60/',
nickname: '1111'
}
return {
background: options.data?.bgImg,
list: [
{
name: 'avatar',
type: 'image',
val: userInfo.avatar,
x: width * 0.064,
y: width * 0.064,
width: 60,
height: 60,
d: 60,
},
{
name: 'nickname',
type: 'text',
val: userInfo.nickname,
x: width * 0.28,
y: width * 0.1,
paintbrushProps: {
fillStyle: '#333',
font: {
fontSize: 14
},
},
},
{
name: 'hint',
type: 'text',
val: options.data?.hint,
x: width * 0.28,
y: width * 0.18,
paintbrushProps: {
fillStyle: '#999',
font: {
fontSize: 10
},
},
},
{
name: 'wxacode',
type: 'image',
val: options.data?.qrCode,
x: width * 0.2,
y: width * 0.38,
width: width * 0.6,
height: width * 0.6,
// size: width * 0.6,
},
],
};
};
export function getPosterData(options) {
switch (options.type) {
case 'invite':
return invite(options);
}
}