useCanvas.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * Shopro + qs-canvas 绘制海报
  3. * @version 1.0.0
  4. * @author lidongtony
  5. * @param {Object} options - 海报参数
  6. * @param {Object} vm - 自定义组件实例
  7. */
  8. import sheep from '@/sheep';
  9. import QSCanvas from 'qs-canvas';
  10. import { getPosterData } from './poster';
  11. export default async function useCanvas(options, vm) {
  12. const width = options.width;
  13. const qsc = new QSCanvas(
  14. {
  15. canvasId: options.canvasId,
  16. width: options.width,
  17. height: options.height,
  18. setCanvasWH: (canvas) => {
  19. options.height = canvas.height;
  20. },
  21. },
  22. vm,
  23. );
  24. let drawer = getPosterData(options);
  25. // 绘制背景图
  26. const background = await qsc.drawImg({
  27. type: 'image',
  28. val: drawer.background,
  29. x: 0,
  30. y: 0,
  31. width,
  32. mode: 'widthFix',
  33. zIndex: 0,
  34. });
  35. await qsc.updateCanvasWH({
  36. width: background.width,
  37. height: background.bottom,
  38. });
  39. let list = drawer.list;
  40. for (let i = 0; i < list.length; i++) {
  41. let item = list[i];
  42. // 绘制文字
  43. if (item.type === 'text') {
  44. await qsc.drawText(item);
  45. }
  46. // 绘制图片
  47. if (item.type === 'image') {
  48. if (item.d) {
  49. qsc.setCircle({
  50. x: item.x,
  51. y: item.y,
  52. d: item.d,
  53. clip: true,
  54. });
  55. }
  56. if (item.r) {
  57. qsc.setRect({
  58. x: item.x,
  59. y: item.y,
  60. height: item.height,
  61. width: item.width,
  62. r: item.r,
  63. clip: true,
  64. });
  65. }
  66. await qsc.drawImg(item);
  67. qsc.restore();
  68. }
  69. // 绘制二维码
  70. if (item.type === 'qrcode') {
  71. await qsc.drawQrCode(item);
  72. }
  73. }
  74. await qsc.draw();
  75. // 延迟执行, 防止不稳定
  76. setTimeout(async () => {
  77. options.src = await qsc.toImage();
  78. }, 100);
  79. return options;
  80. }